Codebase list libcommons-lang3-java / b3b153f
Imported Upstream version 3.2.1 Emmanuel Bourg 10 years ago
266 changed file(s) with 29408 addition(s) and 13227 deletion(s). Raw diff Collapse all Expand all
0 # Maven build files
1 target
2 *.log
3 maven-eclipse.xml
4 build.properties
5 site-content
6
7 # IntelliJ IDEA files
8 .idea
9 .iws
10 *.iml
11 *.ipr
12
13 # Eclipse files
14 .settings
15 .classpath
16 .project
00 Apache Commons Lang
1 Copyright 2001-2011 The Apache Software Foundation
1 Copyright 2001-2014 The Apache Software Foundation
22
3 This product includes software developed by
3 This product includes software developed at
44 The Apache Software Foundation (http://www.apache.org/).
55
66 This product includes software from the Spring Framework,
0 $Id: RELEASE-NOTES.txt 1199820 2011-11-09 16:14:52Z bayard $
1
2 Commons Lang Package
3 Version 3.1
4 Release Notes
0 $Id: RELEASE-NOTES.txt 1555524 2014-01-05 15:24:49Z britter $
1
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16
17
18 Apache Commons Lang
19 Version 3.2.1
20 Release Notes
521
622
723 INTRODUCTION:
824
9 This document contains the release notes for the 3.1 version of Apache Commons Lang.
10 Commons Lang is a set of utility functions and reusable components that should be of use in any
11 Java environment.
12
13 Lang 3.0 and onwards now targets Java 5.0, making use of features that arrived with Java 5.0 such as generics,
14 variable arguments, autoboxing, concurrency and formatted output.
25 This document contains the release notes for the 3.2.1 version of
26 Apache Commons Lang. Commons Lang is a set of utility functions and reusable
27 components that should be of use in any Java environment. Commons Lang 3.2.1
28 at least requires Java 6.0.
1529
1630 For the advice on upgrading from 2.x to 3.x, see the following page:
1731
1832 http://commons.apache.org/lang/article3_0.html
1933
20 CHANGES IN 3.1
21 ================
22
23 [LANG-760] Add API StringUtils.toString(byte[] intput, String charsetName)
24 [LANG-756] Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and isPrimitiveOrWrapper(Class<?>)
25 [LANG-758] Add an example with whitespace in StringUtils.defaultIfEmpty
26 [LANG-752] Fix createLong() so it behaves like createInteger()
27 [LANG-751] Include the actual type in the Validate.isInstance and isAssignableFrom exception messages
28 [LANG-748] Deprecating chomp(String, String)
29 [LANG-736] CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY
30 [LANG-695] SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system
31
32 BUG FIXES IN 3.1
33 ==================
34
35 [LANG-749] Incorrect Bundle-SymbolicName in Manifest
36 [LANG-746] NumberUtils does not handle upper-case hex: 0X and -0X
37 [LANG-744] StringUtils throws java.security.AccessControlException on Google App Engine
38 [LANG-741] Ant build has wrong component.name
39 [LANG-698] Document that the Mutable numbers don't work as expected with String.format
34 BUG FIXES
35 ===========
36
37 o LANG-937: Fix missing Hamcrest dependency in Ant Build
38 o LANG-941: Test failure in LocaleUtilsTest when building with JDK 8
39 o LANG-942: Test failure in FastDateParserTest and FastDateFormat_ParserTest
40 when building with JDK8. Thanks to Bruno P. Kinoshita,
41 Henri Yandell.
42 o LANG-938: Build fails with test failures when building with JDK 8
43
44 Release Notes for version 3.2
45
46 COMPATIBILITY WITH 3.1
47 ========================
48
49 This release introduces backwards incompatible changes in
50 org.apache.commons.lang3.time.FastDateFormat:
51 o Method 'protected java.util.List parsePattern()' has been removed
52 o Method 'protected java.lang.String parseToken(java.lang.String, int[])' has
53 been removed
54 o Method 'protected org.apache.commons.lang3.time.FastDateFormat$NumberRule
55 selectNumberRule(int, int)' has been removed
56
57 These changes were the result of [LANG-462]. It is assumed that this change
58 will not break clients as Charles Honton pointed out on 25/Jan/12:
59 "
60 1. Methods "FastDateFormat$NumberRule selectNumberRule(int, int)" and
61 "List<Rule> parsePattern()" couldn't have been overridden because
62 NumberRule and Rule were private to FastDateFormat.
63 2. Due to the factory pattern used, it's unlikely other two methods would have
64 been overridden.
65 3. The four methods are highly implementation specific. I consider it a
66 mistake that the methods were exposed.
67 "
68 For more information see https://issues.apache.org/jira/browse/LANG-462.
69
70 NEW FEATURES
71 ==============
72
73 o LANG-934: Add removeFinalModifier to FieldUtils
74 o LANG-863: Method returns number of inheritance hops between parent and
75 subclass. Thanks to Daneel S. Yaitskov.
76 o LANG-774: Added isStarted, isSuspended and isStopped to StopWatch.
77 Thanks to Erhan Bagdemir.
78 o LANG-848: Added StringUtils.isBlank/isEmpty CharSequence... methods.
79 Thanks to Alexander Muthmann.
80 o LANG-926: Added ArrayUtils.reverse(array, from, to) methods.
81 o LANG-795: StringUtils.toString(byte[], String) deprecated in favour of a new
82 StringUtils.toString(byte[], CharSet). Thanks to Aaron Digulla.
83 o LANG-893: StrSubstitutor now supports default values for variables.
84 Thanks to Woonsan Ko.
85 o LANG-913: Adding .gitignore to commons-lang. Thanks to Allon Mureinik.
86 o LANG-837: Add ObjectUtils.toIdentityString methods that support
87 StringBuilder, StrBuilder, and Appendable.
88 o LANG-886: Added CharSetUtils.containsAny(String, String).
89 o LANG-797: Added escape/unescapeJson to StringEscapeUtils.
90 o LANG-875: Added appendIfMissing and prependIfMissing methods to StringUtils.
91 o LANG-870: Add StringUtils.LF and StringUtils.CR values.
92 o LANG-873: Add FieldUtils getAllFields() to return all the fields defined in
93 the given class and super classes.
94 o LANG-835: StrBuilder should support StringBuilder as an input parameter.
95 o LANG-857: StringIndexOutOfBoundsException in CharSequenceTranslator.
96 o LANG-856: Code refactoring in NumberUtils.
97 o LANG-855: NumberUtils#createBigInteger does not allow for hex and octal
98 numbers.
99 o LANG-854: NumberUtils#createNumber - does not allow for hex numbers to be
100 larger than Long.
101 o LANG-853: StringUtils join APIs for primitives.
102 o LANG-841: Add StringUtils API to call String.replaceAll in DOTALL a.k.a.
103 single-line mode.
104 o LANG-825: Create StrBuilder APIs similar to
105 String.format(String, Object...).
106 o LANG-675: Add Triple class (ternary version of Pair).
107 o LANG-462: FastDateFormat supports parse methods.
108
109 BUG FIXES
110 ===========
111
112 o LANG-932: Spelling fixes. Thanks to Ville Skyttä.
113 o LANG-929: OctalUnescaper tried to parse all of \279.
114 o LANG-928: OctalUnescaper had bugs when parsing octals starting with a zero.
115 o LANG-905: EqualsBuilder returned true when comparing arrays, even when the
116 elements are different.
117 o LANG-917: Fixed exception when combining custom and choice format in
118 ExtendedMessageFormat. Thanks to Arne Burmeister.
119 o LANG-902: RandomStringUtils.random javadoc was incorrectly promising letters
120 and numbers would, as opposed to may, appear Issue:. Thanks to
121 Andrzej Winnicki.
122 o LANG-921: BooleanUtils.xor(boolean...) produces wrong results.
123 o LANG-896: BooleanUtils.toBoolean(String str) javadoc is not updated. Thanks
124 to Mark Bryan Yu.
125 o LANG-879: LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese"
126 of JDK7.
127 o LANG-836: StrSubstitutor does not support StringBuilder or CharSequence.
128 Thanks to Arnaud Brunet.
129 o LANG-693: Method createNumber from NumberUtils doesn't work for floating
130 point numbers other than Float Issue: LANG-693. Thanks to
131 Calvin Echols.
132 o LANG-887: FastDateFormat does not use the locale specific cache correctly.
133 o LANG-754: ClassUtils.getShortName(String) will now only do a reverse lookup
134 for array types.
135 o LANG-881: NumberUtils.createNumber() Javadoc says it does not work for octal
136 numbers.
137 o LANG-865: LocaleUtils.toLocale does not parse strings starting with an
138 underscore.
139 o LANG-858: StringEscapeUtils.escapeJava() and escapeEcmaScript() do not
140 output the escaped surrogate pairs that are Java parsable.
141 o LANG-849: FastDateFormat and FastDatePrinter generates Date objects
142 wastefully.
143 o LANG-845: Spelling fixes.
144 o LANG-844: Fix examples contained in javadoc of StringUtils.center methods.
145 o LANG-832: FastDateParser does not handle unterminated quotes correctly.
146 o LANG-831: FastDateParser does not handle white-space properly.
147 o LANG-830: FastDateParser could use \Q \E to quote regexes.
148 o LANG-828: FastDateParser does not handle non-Gregorian calendars properly.
149 o LANG-826: FastDateParser does not handle non-ASCII digits correctly.
150 o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--".
151 o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar
152 instances passed to format().
153 o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8.
154 o LANG-813: StringUtils.equalsIgnoreCase doesn't check string reference
155 equality.
156 o LANG-810: StringUtils.join() endIndex, bugged for loop.
157 o LANG-807: RandomStringUtils throws confusing IAE when end <= start.
158 o LANG-805: RandomStringUtils.random(count, 0, 0, false, false, universe,
159 random) always throws java.lang.ArrayIndexOutOfBoundsException.
160 o LANG-802: LocaleUtils - unnecessary recursive call in SyncAvoid class.
161 o LANG-800: Javadoc bug in DateUtils#ceiling for Calendar and Object versions.
162 o LANG-788: SerializationUtils throws ClassNotFoundException when cloning
163 primitive classes.
164 o LANG-786: StringUtils equals() relies on undefined behavior.
165 o LANG-783: Documentation bug: StringUtils.split.
166 o LANG-777: jar contains velocity template of release notes.
167 o LANG-776: TypeUtilsTest contains incorrect type assignability assertion.
168 o LANG-775: TypeUtils.getTypeArguments() misses type arguments for
169 partially-assigned classes.
170 o LANG-773: ImmutablePair doc contains nonsense text.
171 o LANG-772: ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text.
172 o LANG-765: EventListenerSupport.ProxyInvocationHandler no longer defines
173 serialVersionUID.
174 o LANG-764: StrBuilder is now serializable.
175 o LANG-761: Fix Javadoc Ant warnings.
176 o LANG-747: NumberUtils does not handle Long Hex numbers.
177 o LANG-743: Javadoc bug in static inner class DateIterator.
178
179 CHANGES
180 =========
181
182 o LANG-931: Misleading Javadoc comment in StrBuilderReader class. Thanks
183 to Christoph Schneegans.
184 o LANG-910: StringUtils.normalizeSpace now handles non-breaking spaces
185 (Unicode 00A0). Thanks to Timur Yarosh.
186 o LANG-804: Redundant check for zero in HashCodeBuilder ctor. Thanks to
187 Allon Mureinik.
188 o LANG-884: Simplify FastDateFormat; eliminate boxing.
189 o LANG-882: LookupTranslator now works with implementations of CharSequence
190 other than String.
191 o LANG-846: Provide CharSequenceUtils.regionMatches with a proper green
192 implementation instead of inefficiently converting to Strings.
193 o LANG-839: ArrayUtils removeElements methods use unnecessary HashSet.
194 o LANG-838: ArrayUtils removeElements methods clone temporary index arrays
195 unnecessarily.
196 o LANG-799: DateUtils#parseDate uses default locale; add Locale support.
197 o LANG-798: Use generics in SerializationUtils.
198
199 CHANGES WITHOUT TICKET
200 ========================
201
202 o Fixed URLs in javadoc to point to new oracle.com pages
203
204
205 Release Notes for version 3.1
206
207 NEW FEATURES
208 ==============
209
210 o LANG-801: Add Conversion utility to convert between data types on byte level
211 o LANG-760: Add API StringUtils.toString(byte[] intput, String charsetName)
212 o LANG-756: Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and
213 isPrimitiveOrWrapper(Class<?>)
214 o LANG-695: SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system
215
216 BUG FIXES
217 ===========
218
219 o LANG-749: Incorrect Bundle-SymbolicName in Manifest
220 o LANG-746: NumberUtils does not handle upper-case hex: 0X and -0X
221 o LANG-744: StringUtils throws java.security.AccessControlException on Google
222 App Engine
223 o LANG-741: Ant build has wrong component.name
224 o LANG-698: Document that the Mutable numbers don't work as expected with
225 String.format
226
227 CHANGES
228 =========
229
230 o LANG-758: Add an example with whitespace in StringUtils.defaultIfEmpty
231 o LANG-752: Fix createLong() so it behaves like createInteger()
232 o LANG-751: Include the actual type in the Validate.isInstance and
233 isAssignableFrom exception messages
234 o LANG-748: Deprecating chomp(String, String)
235 o LANG-736: CharUtils static final array CHAR_STRING is not needed to compute
236 CHAR_STRING_ARRAY
237
238
239 Release Notes for version 3.0
240
241 ADDITIONS
242 ===========
243
244 o LANG-276: MutableBigDecimal and MutableBigInteger.
245 o LANG-285: Wish : method unaccent.
246 o LANG-358: ObjectUtils.coalesce.
247 o LANG-386: LeftOf/RightOfNumber in Range convenience methods necessary.
248 o LANG-435: Add ClassUtils.isAssignable() variants with autoboxing.
249 o LANG-444: StringUtils.emptyToNull.
250 o LANG-482: Enhance StrSubstitutor to support nested ${var-${subvr}} expansion
251 o LANG-482: StrSubstitutor now supports substitution in variable names.
252 o LANG-496: A generic implementation of the Lazy initialization pattern.
253 o LANG-497: Addition of ContextedException and ContextedRuntimeException.
254 o LANG-498: Add StringEscapeUtils.escapeText() methods.
255 o LANG-499: Add support for the handling of ExecutionExceptions.
256 o LANG-501: Add support for background initialization.
257 o LANG-529: Add a concurrent package.
258 o LANG-533: Validate: support for validating blank strings.
259 o LANG-537: Add ArrayUtils.toArray to create generic arrays.
260 o LANG-545: Add ability to create a Future for a constant.
261 o LANG-546: Add methods to Validate to check whether the index is valid for
262 the array/list/string.
263 o LANG-553: Add TypeUtils class to provide utility code for working with generic
264 types.
265 o LANG-559: Added isAssignableFrom and isInstanceOf validation methods.
266 o LANG-559: Added validState validation method.
267 o LANG-560: New TimedSemaphore class.
268 o LANG-582: Provide an implementation of the ThreadFactory interface.
269 o LANG-588: Create a basic Pair<L, R> class.
270 o LANG-594: DateUtils equal & compare functions up to most significant field.
271 o LANG-601: Add Builder Interface / Update Builders to Implement It.
272 o LANG-609: Support lazy initialization using atomic variables
273 o LANG-610: Extend exception handling in ConcurrentUtils to runtime exceptions.
274 o LANG-614: StringUtils.endsWithAny method
275 o LANG-640: Add normalizeSpace to StringUtils
276 o LANG-644: Provide documentation about the new concurrent package
277 o LANG-649: BooleanUtils.toBooleanObject to support single character input
278 o LANG-651: Add AnnotationUtils
279 o LANG-653: Provide a very basic ConcurrentInitializer implementation
280 o LANG-655: Add StringUtils.defaultIfBlank()
281 o LANG-667: Add a Null-safe compare() method to ObjectUtils
282 o LANG-676: Documented potential NPE if auto-boxing occurs for some BooleanUtils
283 methods
284 o LANG-678: Add support for ConcurrentMap.putIfAbsent()
285 o LANG-692: Add hashCodeMulti varargs method
286 o LANG-697: Add FormattableUtils class
287 o LANG-684: Levenshtein Distance Within a Given Threshold
288
289 REMOVALS
290 ==========
291
292 o LANG-438: Remove @deprecateds.
293 o LANG-492: Remove code handled now by the JDK.
294 o LANG-493: Remove code that does not hold enough value to remain.
295 o LANG-590: Remove JDK 1.2/1.3 bug handling in
296 StringUtils.indexOf(String, String, int).
297 o LANG-673: WordUtils.abbreviate() removed
298 o LANG-691: Removed DateUtils.UTC_TIME_ZONE
299
300 IMPROVEMENTS
301 ==============
302
303 o LANG-290: EnumUtils for JDK 5.0.
304 o LANG-336: Finally start using generics.
305 o LANG-355: StrBuilder should implement CharSequence and Appendable.
306 o LANG-396: Investigate for vararg usages.
307 o LANG-424: Improve Javadoc for StringUtils class.
308 o LANG-458: Refactor Validate.java to eliminate code redundancy.
309 o LANG-479: Document where in SVN trunk is.
310 o LANG-504: bring ArrayUtils.isEmpty to the generics world.
311 o LANG-505: Rewrite StringEscapeUtils.
312 o LANG-507: StringEscapeUtils.unescapeJava should support \u+ notation.
313 o LANG-510: Convert StringUtils API to take CharSequence.
314 o LANG-513: Better EnumUtils.
315 o LANG-528: Mutable classes should implement an appropriately typed Mutable
316 interface.
317 o LANG-539: Compile commons.lang for CDC 1.1/Foundation 1.1.
318 o LANG-540: Make NumericEntityEscaper immutable.
319 o LANG-541: Replace StringBuffer with StringBuilder.
320 o LANG-548: Use Iterable on API instead of Collection.
321 o LANG-551: Replace Range classes with generic version.
322 o LANG-562: Change Maven groupId.
323 o LANG-563: Change Java package name.
324 o LANG-570: Do the test cases really still require main() and suite() methods?
325 o LANG-579: Add new Validate methods.
326 o LANG-599: ClassUtils.getClass(): Allow Dots as Inner Class Separators.
327 o LANG-605: DefaultExceptionContext overwrites values in recursive situations.
328 o LANG-668: Change ObjectUtils min() & max() functions to use varargs rather
329 than just two parameters
330 o LANG-681: Push down WordUtils to "text" sub-package.
331 o LANG-711: Add includeantruntime=false to javac targets to quell warnings in
332 ant 1.8.1 and better (and modest performance gain).
333 o LANG-713: Increase test coverage of FieldUtils read methods and tweak
334 javadoc.
335 o LANG-718: build.xml Java 1.5+ updates.
336
337 BUG FIXES
338 ===========
339
340 o LANG-11: Depend on JDK 1.5+.
341 o LANG-302: StrBuilder does not implement clone().
342 o LANG-339: StringEscapeUtils.escapeHtml() escapes multibyte characters like
343 Chinese, Japanese, etc.
344 o LANG-369: ExceptionUtils not thread-safe.
345 o LANG-418: Javadoc incorrect for StringUtils.endsWithIgnoreCase.
346 o LANG-428: StringUtils.isAlpha, isAlphanumeric and isNumeric now return false
347 for ""
348 o LANG-439: StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20).
349 o LANG-448: Lower Ascii Characters don't get encoded by Entities.java.
350 o LANG-468: JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder).
351 o LANG-474: Fixes for thread safety.
352 o LANG-478: StopWatch does not resist to system time changes.
353 o LANG-480: StringEscapeUtils.escapeHtml incorrectly converts unicode
354 characters above U+00FFFF into 2 characters.
355 o LANG-481: Possible race-conditions in hashCode of the range classes.
356 o LANG-564: Improve StrLookup API documentation.
357 o LANG-568: @SuppressWarnings("unchecked") is used too generally.
358 o LANG-571: ArrayUtils.add(T[: array, T element) can create unexpected
359 ClassCastException.
360 o LANG-585: exception.DefaultExceptionContext.getFormattedExceptionMessage
361 catches Throwable.
362 o LANG-596: StrSubstitutor should also handle the default properties of a
363 java.util.Properties class
364 o LANG-600: Javadoc is incorrect for public static int
365 lastIndexOf(String str, String searchStr).
366 o LANG-602: ContextedRuntimeException no longer an 'unchecked' exception.
367 o LANG-606: EqualsBuilder causes StackOverflowException.
368 o LANG-608: Some StringUtils methods should take an int character instead of
369 char to use String API features.
370 o LANG-617: StringEscapeUtils.escapeXML() can't process UTF-16 supplementary
371 characters
372 o LANG-624: SystemUtils.getJavaVersionAsFloat throws
373 StringIndexOutOfBoundsException on Android runtime/Dalvik VM
374 o LANG-629: Charset may not be threadsafe, because the HashSet is not synch.
375 o LANG-638: NumberUtils createNumber throws a StringIndexOutOfBoundsException
376 when argument containing "e" and "E" is passed in
377 o LANG-643: Javadoc StringUtils.left() claims to throw on negative len, but
378 doesn't
379 o LANG-645: FastDateFormat.format() outputs incorrect week of year because
380 locale isn't respected
381 o LANG-646: StringEscapeUtils.unescapeJava doesn't handle octal escapes and
382 Unicode with extra u
383 o LANG-656: Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect
384 o LANG-658: Some Entitys like &Ouml; are not matched properly against its
385 ISO8859-1 representation
386 o LANG-659: EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212
387 ISOtech
388 o LANG-66: StringEscaper.escapeXml() escapes characters > 0x7f.
389 o LANG-662: org.apache.commons.lang3.math.Fraction does not reduce
390 (Integer.MIN_VALUE, 2^k)
391 o LANG-663: org.apache.commons.lang3.math.Fraction does not always succeed in
392 multiplyBy and divideBy
393 o LANG-664: NumberUtils.isNumber(String) is not right when the String is
394 "1.1L"
395 o LANG-672: Doc bug in DateUtils#ceiling
396 o LANG-677: DateUtils.isSameLocalTime compares using 12 hour clock and not
397 24 hour
398 o LANG-685: EqualsBuilder synchronizes on HashCodeBuilder.
399 o LANG-703: StringUtils.join throws NPE when toString returns null for one of
400 objects in collection
401 o LANG-710: StringIndexOutOfBoundsException when calling unescapeHtml4("&#03")
402 o LANG-714: StringUtils doc/comment spelling fixes.
403 o LANG-715: CharSetUtils.squeeze() speedup.
404 o LANG-716: swapCase and *capitalize speedups.
405
406
407 Historical list of changes: http://commons.apache.org/lang/changes-report.html
408
409 For complete information on Commons Lang, including instructions on how to
410 submit bug reports, patches, or suggestions for improvement, see the
411 Apache Commons Lang website:
412
413 http://commons.apache.org/lang/
414
415 Have fun!
416 -Apache Commons Lang team
417
2121
2222 # Repository base path - unnecessary if full jar paths are provided below
2323 repository=${user.home}/.m2/repository
24 junit.home=${repository}/junit/junit/4.10/
25 easymock.home=${repository}/org/easymock/easymock/2.5.2/
26 commons-io.home=${repository}/commons-io/commons-io/2.0.1/
24 junit.home=${repository}/junit/junit/4.11/
25 easymock.home=${repository}/org/easymock/easymock/3.2/
26 commons-io.home=${repository}/commons-io/commons-io/2.4/
27 hamcrest.home=${repository}/org/hamcrest/hamcrest-core/1.3/
1919 -->
2020 <!--
2121 "Lang" component of the Apache Commons Subproject
22 $Id: build.xml 1148152 2011-07-19 04:32:56Z bayard $
22 $Id: build.xml 1554848 2014-01-02 17:06:53Z britter $
2323 -->
2424 <project name="Lang" default="compile" basedir=".">
2525
2929 <property file="${basedir}/build.properties"/>
3030 <property file="${basedir}/default.properties"/>
3131 <property name="jdk.javadoc" value="http://download.oracle.com/javase/1.5.0/docs/api/"/>
32 <property name="collections.javadoc" value="http://commons.apache.org/collections/api-release/"/>
3233
3334 <!-- ========== Construct compile classpath =============================== -->
3435 <path id="compile.classpath">
4041 <pathelement location="${build.home}/classes"/>
4142 <pathelement location="${build.home}/tests"/>
4243 <pathelement location="${junit.jar}"/>
43 <pathelement location="${easymock.jar}"/>
44 <pathelement location="${commons-io.jar}"/>
44 <pathelement location="${easymock.jar}"/>
45 <pathelement location="${commons-io.jar}"/>
46 <pathelement location="${hamcrest.jar}"/>
4547 </path>
4648
4749 <!-- ========== Executable Targets ======================================== -->
6264 <classpath refid="compile.classpath"/>
6365 </javac>
6466 <copy todir="${build.home}/classes" filtering="on">
65 <fileset dir="${source.home}" excludes="**/*.java"/>
67 <fileset dir="${source.home}" excludes="**/*.java,**/*.html"/>
6668 </copy>
6769 </target>
6870
118120 windowtitle="Lang ${component.version}"
119121 bottom="Copyright &amp;copy; 2001-${current.year} - Apache Software Foundation"
120122 use="true"
121 link="${jdk.javadoc}"
122123 encoding="${compile.encoding}"
123124 source="${compile.source}">
124125 <classpath refid="compile.classpath"/>
126 <link href="${jdk.javadoc}"/>
127 <link href="${collections.javadoc}"/>
125128 </javadoc>
126129 </target>
127130
1414 # limitations under the License.
1515 #
1616
17 # $Id: default.properties 1200190 2011-11-10 06:56:02Z bayard $
17 # $Id: default.properties 1555582 2014-01-05 16:59:30Z britter $
1818
1919 # The location of the "junit.jar" JAR file
20 junit.jar = ${junit.home}/junit-4.10.jar
20 junit.jar = ${junit.home}/junit-4.11.jar
2121
2222 # The location of the Easymock jar
23 easymock.jar = ${easymock.home}/easymock-2.5.2.jar
23 easymock.jar = ${easymock.home}/easymock-3.2.jar
2424
2525 # The location of the Commons-IO jar
26 commons-io.jar = ${commons-io.home}/commons-io-2.0.1.jar
26 commons-io.jar = ${commons-io.home}/commons-io-2.4.jar
27
28 # The location of Hamcrest jar
29 hamcrest.jar = ${hamcrest.home}/hamcrest-core-1.3.jar
2730
2831 # Whether or not to fork tests
2932 junit.fork = true
3841 component.title = Core Language Utilities
3942
4043 # The current version number of this component
41 component.version = 3.1
44 component.version = 3.2.1
4245
4346 # The name that is used to create the jar file
4447 final.name = ${component.name}-${component.version}
6972 # In particular, if you use JDK 1.4+ the generated classes will not be usable
7073 # for a 1.1 Java VM unless you explicitly set this attribute to the value 1.1
7174 # (which is the default value for JDK 1.1 to 1.3).
72 compile.target = 1.5
75 compile.target = 1.6
7376
7477 # Specifies the source version for the Java compiler.
7578 # Corresponds to the source attribute for the ant javac task.
7679 # Valid values are 1.3, 1.4, 1.5.
77 compile.source = 1.5
80 compile.source = 1.6
7881
7982 # Specifies the source encoding.
8083 compile.encoding = ISO-8859-1
2222 <category rdf:resource="http://projects.apache.org/category/library"/>
2323 <license rdf:resource="http://usefulinc.com/doap/licenses/asl20"/>
2424 <bug-database rdf:resource="http://issues.apache.org/jira/browse/LANG"/>
25 <download-page rdf:resource="http://commons.apache.org/downloads/download_lang.cgi"/>
25 <download-page rdf:resource="http://commons.apache.org/lang/download_lang.cgi"/>
2626 <asfext:pmc rdf:resource="http://commons.apache.org/"/>
2727 <shortdesc xml:lang="en">Java Common Components</shortdesc>
2828 <description xml:lang="en">
3737 </SVNRepository>
3838 </repository>
3939 <release>
40 <Version>
41 <name>commons-lang</name>
42 <created>2014-01-01</created>
43 <revision>3.2</revision>
44 </Version>
45 <Version>
46 <name>commons-lang</name>
47 <created>2011-11-14</created>
48 <revision>3.1</revision>
49 </Version>
4050 <Version>
4151 <name>commons-lang</name>
4252 <created>2011-07-18</created>
122122 <Bug pattern="DM_NUMBER_CTOR" />
123123 </Match>
124124
125 <!-- Reason: FindBugs 2.0.2 used in maven-findbugs-plugin 2.5.2 seems to have problems with detection of default cases
126 in switch statements. All the excluded methods have switch statements that conatin a default case. -->
127 <Match>
128 <Class name="org.apache.commons.lang3.math.NumberUtils"/>
129 <Method name="createNumber" />
130 <Bug pattern="SF_SWITCH_NO_DEFAULT" />
131 </Match>
132 <Match>
133 <Class name="org.apache.commons.lang3.text.ExtendedMessageFormat"/>
134 <Method name="insertFormats" />
135 <Bug pattern="SF_SWITCH_NO_DEFAULT" />
136 </Match>
137 <Match>
138 <Class name="org.apache.commons.lang3.time.FastDateParser"/>
139 <Method name="getStrategy" />
140 <Bug pattern="SF_SWITCH_NO_DEFAULT" />
141 </Match>
142
125143 </FindBugsFilter>
00 <?xml version="1.0" encoding="UTF-8"?>
1 <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with
2 this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
3 "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
4 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
5 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations
6 under the License. -->
1 <!--
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 -->
717 <project
818 xmlns="http://maven.apache.org/POM/4.0.0"
919 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1121 <parent>
1222 <groupId>org.apache.commons</groupId>
1323 <artifactId>commons-parent</artifactId>
14 <version>22</version>
24 <version>32</version>
1525 </parent>
1626 <modelVersion>4.0.0</modelVersion>
1727 <groupId>org.apache.commons</groupId>
1828 <artifactId>commons-lang3</artifactId>
19 <version>3.1</version>
20 <name>Commons Lang</name>
29 <version>3.2.1</version>
30 <name>Apache Commons Lang</name>
2131
2232 <inceptionYear>2001</inceptionYear>
2333 <description>
24 Commons Lang, a package of Java utility classes for the
34 Apache Commons Lang, a package of Java utility classes for the
2535 classes that are in java.lang's hierarchy, or are considered to be so
2636 standard as to justify existence in java.lang.
2737 </description>
2838
29 <url>http://commons.apache.org/lang/</url>
39 <url>http://commons.apache.org/proper/commons-lang/</url>
3040
3141 <issueManagement>
3242 <system>jira</system>
97107 </roles>
98108 </developer>
99109 <developer>
100 <name>Phil Steitz</name>
101 <id>psteitz</id>
102 <organization />
103 <roles>
104 <role>Java Developer</role>
105 </roles>
106 </developer>
107 <developer>
108110 <name>Fredrik Westermarck</name>
109111 <id>fredrik</id>
110112 <email />
162164 <role>Java Developer</role>
163165 </roles>
164166 </developer>
167 <developer>
168 <name>Benedikt Ritter</name>
169 <id>britter</id>
170 <email>britter@apache.org</email>
171 <roles>
172 <role>Java Developer</role>
173 </roles>
174 </developer>
165175 </developers>
166176 <contributors>
167177 <contributor>
255265 <name>Michael Heuer</name>
256266 </contributor>
257267 <contributor>
268 <name>Chas Honton</name>
269 </contributor>
270 <contributor>
258271 <name>Chris Hyzer</name>
259272 </contributor>
260273 <contributor>
264277 <name>Marc Johnson</name>
265278 </contributor>
266279 <contributor>
280 <name>Duncan Jones</name>
281 </contributor>
282 <contributor>
267283 <name>Shaun Kalley</name>
268284 </contributor>
269285 <contributor>
402418 <name>Masato Tezuka</name>
403419 </contributor>
404420 <contributor>
421 <name>Daniel Trebbien</name>
422 </contributor>
423 <contributor>
405424 <name>Jeff Varszegi</name>
406425 </contributor>
407426 <contributor>
418437 </contributor>
419438 <contributor>
420439 <name>Derek C. Ashmore</name>
440 </contributor>
441 <contributor>
442 <name>Sebastien Riou</name>
443 </contributor>
444 <contributor>
445 <name>Allon Mureinik</name>
421446 </contributor>
422447 </contributors>
423448
426451 <dependency>
427452 <groupId>junit</groupId>
428453 <artifactId>junit</artifactId>
429 <version>4.10</version>
454 <version>4.11</version>
430455 <scope>test</scope>
431456 </dependency>
432457
433458 <dependency>
434459 <groupId>commons-io</groupId>
435460 <artifactId>commons-io</artifactId>
436 <version>2.1</version>
461 <version>2.4</version>
437462 <scope>test</scope>
438463 </dependency>
439464
440465 <dependency>
441466 <groupId>org.easymock</groupId>
442467 <artifactId>easymock</artifactId>
443 <version>3.0</version>
468 <version>3.2</version>
444469 <scope>test</scope>
445470 </dependency>
446471 </dependencies>
447472
473 <distributionManagement>
474 <site>
475 <id>apache.website</id>
476 <name>Apache Commons Site</name>
477 <url>scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-lang/</url>
478 </site>
479 </distributionManagement>
480
448481 <properties>
449482 <project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
450483 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
451 <maven.compile.source>1.5</maven.compile.source>
452 <maven.compile.target>1.5</maven.compile.target>
484 <maven.compiler.source>1.6</maven.compiler.source>
485 <maven.compiler.target>1.6</maven.compiler.target>
486 <!--
487 This is also used to generate download_xxx file name.
488 To override this when generating the download page:
489
490 mvn commons:download-page -Dcommons.componentid=lang
491
492 The above seems to change the download page name but not any other
493 properties that depend on the componentid.
494 -->
453495 <commons.componentid>lang3</commons.componentid>
454 <commons.release.version>3.1</commons.release.version>
455 <commons.release.desc>(Java 5.0+)</commons.release.desc>
496 <!-- Current 3.x release series -->
497 <commons.release.version>3.2.1</commons.release.version>
498 <commons.release.desc>(Java 6.0+)</commons.release.desc>
499 <!-- Previous 2.x release series -->
500 <commons.release.2.version>2.6</commons.release.2.version>
501 <commons.release.2.desc>(Requires Java 1.2 or later)</commons.release.2.desc>
502 <!-- Override generated name -->
503 <commons.release.2.name>commons-lang-${commons.release.2.version}</commons.release.2.name>
456504 <commons.jira.id>LANG</commons.jira.id>
457505 <commons.jira.pid>12310481</commons.jira.pid>
506
507 <commons.site.path>lang</commons.site.path>
508 <commons.scmPubUrl>https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-lang</commons.scmPubUrl>
509 <commons.scmPubCheckoutDirectory>site-content</commons.scmPubCheckoutDirectory>
458510 </properties>
459511
460512
470522 <includes>
471523 <include>**/*Test.java</include>
472524 </includes>
525 <runOrder>random</runOrder>
473526 </configuration>
474527 </execution>
475528 <!-- <execution> <id>security-manager-test</id> <phase>integration-test</phase> <goals> <goal>test</goal> </goals> <configuration>
498551 </execution>
499552 </executions>
500553 </plugin>
554 <plugin>
555 <groupId>org.apache.maven.plugins</groupId>
556 <artifactId>maven-scm-publish-plugin</artifactId>
557 <configuration>
558 <ignorePathsToDelete>
559 <ignorePathToDelete>javadocs</ignorePathToDelete>
560 </ignorePathsToDelete>
561 </configuration>
562 </plugin>
501563 </plugins>
564
502565 </build>
503566
504567 <reporting>
505568 <plugins>
506569 <plugin>
507 <groupId>org.apache.maven.plugins</groupId>
508 <artifactId>maven-changes-plugin</artifactId>
509 <version>2.6</version>
570 <artifactId>maven-checkstyle-plugin</artifactId>
571 <version>2.9.1</version>
510572 <configuration>
511 <xmlPath>${basedir}/src/site/changes/changes.xml</xmlPath>
512 <issueLinkTemplatePerSystem>
513 <default>%URL%/%ISSUE%</default>
514 </issueLinkTemplatePerSystem>
515 <template>release-notes.vm</template>
516 <templateDirectory>templates</templateDirectory>
517 <!-- Give the output file its proper name -->
518 <announcementFile>RELEASE-NOTES.txt</announcementFile>
573 <configLocation>${basedir}/checkstyle.xml</configLocation>
574 <enableRulesSummary>false</enableRulesSummary>
519575 </configuration>
520576 <reportSets>
521577 <reportSet>
522578 <reports>
523 <report>changes-report</report>
579 <report>checkstyle</report>
524580 </reports>
525581 </reportSet>
526582 </reportSets>
527583 </plugin>
528 <plugin>
529 <artifactId>maven-checkstyle-plugin</artifactId>
530 <version>2.7</version>
531 <configuration>
532 <configLocation>${basedir}/checkstyle.xml</configLocation>
533 <enableRulesSummary>false</enableRulesSummary>
534 </configuration>
535 </plugin>
536584 <!-- Requires setting 'export MAVEN_OPTS="-Xmx512m" ' -->
537585 <plugin>
538586 <groupId>org.codehaus.mojo</groupId>
539587 <artifactId>findbugs-maven-plugin</artifactId>
540 <version>2.3.2</version>
588 <version>2.5.2</version>
541589 <configuration>
542590 <threshold>Normal</threshold>
543591 <effort>Default</effort>
552600 <plugin>
553601 <groupId>org.codehaus.mojo</groupId>
554602 <artifactId>clirr-maven-plugin</artifactId>
555 <version>2.3</version>
603 <version>2.4</version>
556604 <configuration>
557605 <minSeverity>info</minSeverity>
606 <!-- Compare 3.2.1 against 3.1, since point releases never introduce API changes -->
607 <comparisonVersion>3.1</comparisonVersion>
558608 </configuration>
559609 </plugin>
560610 <plugin>
561611 <artifactId>maven-pmd-plugin</artifactId>
562 <version>2.5</version>
612 <version>3.0.1</version>
563613 <configuration>
564614 <targetJdk>${maven.compile.target}</targetJdk>
565615 </configuration>
589639 <artifactId>javancss-maven-plugin</artifactId>
590640 <version>2.0</version>
591641 </plugin>
642 <plugin>
643 <groupId>org.apache.rat</groupId>
644 <artifactId>apache-rat-plugin</artifactId>
645 <configuration>
646 <excludes>
647 <exclude>site-content/**</exclude>
648 <exclude>src/site/resources/download_lang.cgi</exclude>
649 <exclude>src/site/resources/release-notes/RELEASE-NOTES-*.txt</exclude>
650 <exclude>src/test/resources/lang-708-input.txt</exclude>
651 </excludes>
652 </configuration>
653 </plugin>
592654 </plugins>
593655 </reporting>
594656
657 <profiles>
658 <profile>
659 <id>setup-checkout</id>
660 <activation>
661 <file>
662 <missing>site-content</missing>
663 </file>
664 </activation>
665 <build>
666 <plugins>
667 <plugin>
668 <groupId>org.apache.maven.plugins</groupId>
669 <artifactId>maven-antrun-plugin</artifactId>
670 <version>1.7</version>
671 <executions>
672 <execution>
673 <id>prepare-checkout</id>
674 <phase>pre-site</phase>
675 <goals>
676 <goal>run</goal>
677 </goals>
678 <configuration>
679 <tasks>
680 <exec executable="svn">
681 <arg line="checkout --depth immediates ${commons.scmPubUrl} ${commons.scmPubCheckoutDirectory}" />
682 </exec>
683
684 <exec executable="svn">
685 <arg line="update --set-depth exclude ${commons.scmPubCheckoutDirectory}/javadocs" />
686 </exec>
687
688 <pathconvert pathsep=" " property="dirs">
689 <dirset dir="${commons.scmPubCheckoutDirectory}" includes="*" />
690 </pathconvert>
691 <exec executable="svn">
692 <arg line="update --set-depth infinity ${dirs}" />
693 </exec>
694 </tasks>
695 </configuration>
696 </execution>
697 </executions>
698 </plugin>
699 </plugins>
700 </build>
701 </profile>
702 </profiles>
703
595704 </project>
0 <?xml version="1.0"?>
1 <!--
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 -->
17 <document>
18 <properties>
19 <title>Apache Commons Lang Changes</title>
20 </properties>
21 <body>
22
23 <release version="3.2.1" date="2014-01-05" description="Bug fix for 3.2">
24 <action issue="LANG-937" type="fix" dev="britter">Fix missing Hamcrest dependency in Ant Build</action>
25 <action issue="LANG-941" type="fix" dev="britter">Test failure in LocaleUtilsTest when building with JDK 8</action>
26 <action issue="LANG-942" type="fix" dev="britter" due-to="Bruno P. Kinoshita, Henri Yandell">Test failure in FastDateParserTest and FastDateFormat_ParserTest when building with JDK8</action>
27 <action issue="LANG-938" type="fix">Build fails with test failures when building with JDK 8</action>
28 </release>
29
30 <release version="3.2" date="2014-01-01" description="Bug fixes and new features, at least requires Java 6.0">
31 <action issue="LANG-934" type="add" dev="mcucchiara">Add removeFinalModifier to FieldUtils</action>
32 <action issue="LANG-863" type="add" due-to="Daneel S. Yaitskov" dev="sebb">Method returns number of inheritance hops between parent and subclass</action>
33 <action issue="LANG-932" type="fix" due-to="Ville Skyttä" dev="sebb">Spelling fixes</action>
34 <action issue="LANG-931" type="update" dev="britter" due-to="Christoph Schneegans">Misleading Javadoc comment in StrBuilderReader class</action>
35 <action issue="LANG-929" type="fix">OctalUnescaper tried to parse all of \279</action>
36 <action issue="LANG-928" type="fix">OctalUnescaper had bugs when parsing octals starting with a zero</action>
37 <action issue="LANG-905" type="fix">EqualsBuilder returned true when comparing arrays, even when the elements are different</action>
38 <action issue="LANG-774" type="add" due-to="Erhan Bagdemir">Added isStarted, isSuspended and isStopped to StopWatch</action>
39 <action issue="LANG-917" type="fix" due-to="Arne Burmeister">Fixed exception when combining custom and choice format in ExtendedMessageFormat</action>
40 <action issue="LANG-848" type="add" due-to="Alexander Muthmann">Added StringUtils.isBlank/isEmpty CharSequence... methods</action>
41 <action issue="LANG-926" type="add" dev="ggregory">Added ArrayUtils.reverse(array, from, to) methods</action>
42 <action issue="LANG-795" type="add" due-to="Aaron Digulla">StringUtils.toString(byte[], String) deprecated in favour of a new StringUtils.toString(byte[], CharSet)</action>
43 <action issue="LANG-902" type="fix" due-to="Andrzej Winnicki">RandomStringUtils.random javadoc was incorrectly promising letters and numbers would, as opposed to may, appear</action>
44 <action issue="LANG-921" type="fix" dev="britter">BooleanUtils.xor(boolean...) produces wrong results</action>
45 <action issue="LANG-910" type="update" due-to="Timur Yarosh">StringUtils.normalizeSpace now handles non-breaking spaces (Unicode 00A0)</action>
46 <action issue="LANG-804" type="update" dev="britter" due-to="Allon Mureinik">Redundant check for zero in HashCodeBuilder ctor</action>
47 <action issue="LANG-893" type="add" dev="oheger" due-to="Woonsan Ko">StrSubstitutor now supports default values for variables</action>
48 <action issue="LANG-913" type="add" dev="britter" due-to="Allon Mureinik">Adding .gitignore to commons-lang</action>
49 <action issue="LANG-837" type="add">Add ObjectUtils.toIdentityString methods that support StringBuilder, StrBuilder, and Appendable</action>
50 <action issue="LANG-896" type="fix" due-to="Mark Bryan Yu">BooleanUtils.toBoolean(String str) javadoc is not updated</action>
51 <action issue="LANG-879" type="fix">LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese" of JDK7</action>
52 <action issue="LANG-836" type="fix" due-to="Arnaud Brunet">StrSubstitutor does not support StringBuilder or CharSequence</action>
53 <action issue="LANG-693" type="fix" due-to="Calvin Echols">Method createNumber from NumberUtils doesn't work for floating point numbers other than Float</action>
54 <action issue="LANG-887" type="fix">FastDateFormat does not use the locale specific cache correctly</action>
55 <action issue="LANG-884" type="update">Simplify FastDateFormat; eliminate boxing</action>
56 <action issue="LANG-882" type="update">LookupTranslator now works with implementations of CharSequence other than String</action>
57 <action issue="LANG-754" type="fix">ClassUtils.getShortName(String) will now only do a reverse lookup for array types</action>
58 <action issue="LANG-886" type="add">Added CharSetUtils.containsAny(String, String)</action>
59 <action issue="LANG-846" type="update">Provide CharSequenceUtils.regionMatches with a proper green implementation instead of inefficiently converting to Strings</action>
60 <action issue="LANG-797" type="add">Added escape/unescapeJson to StringEscapeUtils</action>
61 <action issue="LANG-875" type="add">Added appendIfMissing and prependIfMissing methods to StringUtils</action>
62 <action issue="LANG-881" type="fix">NumberUtils.createNumber() Javadoc says it does not work for octal numbers</action>
63 <action type="fix">Fixed URLs in javadoc to point to new oracle.com pages</action>
64 <action issue="LANG-870" type="add">Add StringUtils.LF and StringUtils.CR values</action>
65 <action issue="LANG-873" type="add">Add FieldUtils getAllFields() to return all the fields defined in the given class and super classes</action>
66 <action issue="LANG-865" type="fix">LocaleUtils.toLocale does not parse strings starting with an underscore</action>
67 <action issue="LANG-835" type="add">StrBuilder should support StringBuilder as an input parameter</action>
68 <action issue="LANG-858" type="fix">StringEscapeUtils.escapeJava() and escapeEcmaScript() do not output the escaped surrogate pairs that are Java parsable</action>
69 <action issue="LANG-857" type="add">StringIndexOutOfBoundsException in CharSequenceTranslator</action>
70 <action issue="LANG-856" type="add">Code refactoring in NumberUtils</action>
71 <action issue="LANG-855" type="add">NumberUtils#createBigInteger does not allow for hex and octal numbers</action>
72 <action issue="LANG-854" type="add">NumberUtils#createNumber - does not allow for hex numbers to be larger than Long</action>
73 <action issue="LANG-853" type="add">StringUtils join APIs for primitives</action>
74 <action issue="LANG-849" type="fix">FastDateFormat and FastDatePrinter generates Date objects wastefully</action>
75 <action issue="LANG-845" type="fix">Spelling fixes</action>
76 <action issue="LANG-844" type="fix">Fix examples contained in javadoc of StringUtils.center methods</action>
77 <action issue="LANG-841" type="add">Add StringUtils API to call String.replaceAll in DOTALL a.k.a. single-line mode</action>
78 <action issue="LANG-839" type="update">ArrayUtils removeElements methods use unnecessary HashSet</action>
79 <action issue="LANG-838" type="update">ArrayUtils removeElements methods clone temporary index arrays unnecessarily</action>
80 <action issue="LANG-832" type="fix">FastDateParser does not handle unterminated quotes correctly</action>
81 <action issue="LANG-831" type="fix">FastDateParser does not handle white-space properly</action>
82 <action issue="LANG-830" type="fix">FastDateParser could use \Q \E to quote regexes</action>
83 <action issue="LANG-828" type="fix">FastDateParser does not handle non-Gregorian calendars properly</action>
84 <action issue="LANG-826" type="fix">FastDateParser does not handle non-ASCII digits correctly</action>
85 <action issue="LANG-825" type="add">Create StrBuilder APIs similar to String.format(String, Object...)</action>
86 <action issue="LANG-822" type="fix">NumberUtils#createNumber - bad behaviour for leading "--"</action>
87 <action issue="LANG-818" type="fix">FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format()</action>
88 <action issue="LANG-817" type="fix">Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8</action>
89 <action issue="LANG-813" type="fix">StringUtils.equalsIgnoreCase doesn't check string reference equality</action>
90 <action issue="LANG-810" type="fix">StringUtils.join() endIndex, bugged for loop</action>
91 <action issue="LANG-807" type="fix">RandomStringUtils throws confusing IAE when end &lt;= start</action>
92 <action issue="LANG-805" type="fix">RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException</action>
93 <action issue="LANG-802" type="fix">LocaleUtils - unnecessary recursive call in SyncAvoid class.</action>
94 <action issue="LANG-800" type="fix">Javadoc bug in DateUtils#ceiling for Calendar and Object versions.</action>
95 <action issue="LANG-799" type="update">DateUtils#parseDate uses default locale; add Locale support</action>
96 <action issue="LANG-798" type="update">Use generics in SerializationUtils</action>
97 <action issue="LANG-788" type="fix">SerializationUtils throws ClassNotFoundException when cloning primitive classes</action>
98 <action issue="LANG-786" type="fix">StringUtils equals() relies on undefined behavior</action>
99 <action issue="LANG-783" type="fix">Documentation bug: StringUtils.split</action>
100 <action issue="LANG-777" type="fix">jar contains velocity template of release notes</action>
101 <action issue="LANG-776" type="fix">TypeUtilsTest contains incorrect type assignability assertion</action>
102 <action issue="LANG-775" type="fix">TypeUtils.getTypeArguments() misses type arguments for partially-assigned classes</action>
103 <action issue="LANG-773" type="fix">ImmutablePair doc contains nonsense text</action>
104 <action issue="LANG-772" type="fix">ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text</action>
105 <action issue="LANG-765" type="fix">EventListenerSupport.ProxyInvocationHandler no longer defines serialVersionUID</action>
106 <action issue="LANG-764" type="fix">StrBuilder is now serializable</action>
107 <action issue="LANG-761" type="fix">Fix Javadoc Ant warnings</action>
108 <action issue="LANG-747" type="fix">NumberUtils does not handle Long Hex numbers</action>
109 <action issue="LANG-743" type="fix">Javadoc bug in static inner class DateIterator</action>
110 <action issue="LANG-675" type="add">Add Triple class (ternary version of Pair)</action>
111 <action issue="LANG-462" type="add">FastDateFormat supports parse methods</action>
112 </release>
113
114 <release version="3.1" date="2011-11-14" description="November release">
115 <action type="add" issue="LANG-760">Add API StringUtils.toString(byte[] intput, String charsetName)</action>
116 <action type="update" issue="LANG-758">Add an example with whitespace in StringUtils.defaultIfEmpty</action>
117 <action type="add" issue="LANG-756">Add APIs ClassUtils.isPrimitiveWrapper(Class&lt;?&gt;) and isPrimitiveOrWrapper(Class&lt;?&gt;)</action>
118 <action type="update" issue="LANG-752">Fix createLong() so it behaves like createInteger()</action>
119 <action type="update" issue="LANG-751">Include the actual type in the Validate.isInstance and isAssignableFrom exception messages</action>
120 <action type="fix" issue="LANG-749">Incorrect Bundle-SymbolicName in Manifest</action>
121 <action type="update" issue="LANG-748">Deprecating chomp(String, String)</action>
122 <action type="fix" issue="LANG-746">NumberUtils does not handle upper-case hex: 0X and -0X</action>
123 <action type="fix" issue="LANG-744">StringUtils throws java.security.AccessControlException on Google App Engine</action>
124 <action type="fix" issue="LANG-741">Ant build has wrong component.name</action>
125 <action type="update" issue="LANG-736">CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY</action>
126 <action type="fix" issue="LANG-698">Document that the Mutable numbers don't work as expected with String.format</action>
127 <action type="add" issue="LANG-695">SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system</action>
128 </release>
129
130 <release version="3.0.1" date="2011-08-09" description="August release">
131 <action type="fix" issue="LANG-626">SerializationUtils.clone: Fallback to context classloader if class not found in current classloader.</action>
132 <action type="fix" issue="LANG-727">ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6.</action>
133 <action type="fix" issue="LANG-720">StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes.</action>
134 <action type="fix" issue="LANG-708">StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string.</action>
135 <action type="update" issue="LANG-686">Improve exception message when StringUtils.replaceEachRepeatedly detects recursion.</action>
136 <action type="update" issue="LANG-717">Specify source encoding for Ant build.</action>
137 <action type="add" issue="LANG-721">Complement ArrayUtils.addAll() variants with by-index and by-value removal methods.</action>
138 <action type="add" issue="LANG-726">Add Range&lt;T&gt; Range&lt;T&gt;.intersectionWith(Range&lt;T&gt;).</action>
139 <action type="add" issue="LANG-723">Add mode and median Comparable... methods to ObjectUtils.</action>
140 <action type="add" issue="LANG-722">Add BooleanUtils.and + or varargs methods.</action>
141 <action type="add" issue="LANG-730">EnumSet -&gt; bit vector.</action>
142 <action type="fix" issue="LANG-734">The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character.</action>
143 <action type="update" issue="LANG-735">Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char).</action>
144 <action type="add" issue="LANG-737">Missing method getRawMessage for ContextedException and ContextedRuntimeException.</action>
145 <action type="fix" issue="LANG-738">Use internal Java's Number caches instead creating new objects.</action>
146 </release>
147
148 <release version="3.0" date="2011-07-18" description="Backwards incompatible update of Commons Lang to Java 5">
149 <action type="fix" issue="LANG-720">StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes.</action>
150 <action type="update" issue="LANG-718">build.xml Java 1.5+ updates.</action>
151 <action type="fix" issue="LANG-716">swapCase and *capitalize speedups.</action>
152 <action type="fix" issue="LANG-715">CharSetUtils.squeeze() speedup.</action>
153 <action type="fix" issue="LANG-714">StringUtils doc/comment spelling fixes.</action>
154 <action type="update" issue="LANG-713">Increase test coverage of FieldUtils read methods and tweak Javadoc.</action>
155 <action type="fix" issue="LANG-711">Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain).</action>
156 <action type="fix" issue="LANG-710">StringIndexOutOfBoundsException when calling unescapeHtml4("&amp;#03").</action>
157 <action type="fix" issue="LANG-708">StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string.</action>
158 <action type="fix" issue="LANG-703">StringUtils.join throws NPE when toString returns null for one of objects in collection.</action>
159 <action type="add" issue="LANG-697">Add FormattableUtils class.</action>
160 <action type="add">Add ClassUtils.getSimpleName() methods.</action>
161 <action type="add" issue="LANG-692">Add hashCodeMulti varargs method.</action>
162 <action type="remove" issue="LANG-691">Removed DateUtils.UTC_TIME_ZONE.</action>
163 <action type="update" issues="LANG-687">Convert more of the StringUtils API to take CharSequence.</action>
164 <action type="fix" issue="LANG-685">EqualsBuilder synchronizes on HashCodeBuilder.</action>
165 <action type="fix" issue="LANG-428">StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "".</action>
166 <action type="add" issue="LANG-678">Add support for ConcurrentMap.putIfAbsent().</action>
167 <action type="add" issue="LANG-676">Documented potential NPE if auto-boxing occurs for some BooleanUtils methods.</action>
168 <action type="fix" issue="LANG-677">DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour.</action>
169 <action type="add" issue="LANG-610">Extend exception handling in ConcurrentUtils to runtime exceptions.</action>
170 <action type="fix" issue="LANG-624">SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM.</action>
171 <action type="remove" issue="LANG-673">WordUtils.abbreviate() removed.</action>
172 <action type="fix" issue="LANG-672">Doc bug in DateUtils#ceiling.</action>
173 <action type="fix" issue="LANG-646">StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u.</action>
174 <action type="fix" issue="LANG-662">org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k).</action>
175 <action type="fix" issue="LANG-663">org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy.</action>
176 <action type="update" issue="LANG-668">Change ObjectUtils min() &amp; max() functions to use varargs rather than just two parameters.</action>
177 <action type="add" issue="LANG-667">Add a Null-safe compare() method to ObjectUtils.</action>
178 <action type="fix" issue="LANG-664">NumberUtils.isNumber(String) is not right when the String is "1.1L".</action>
179 <action type="fix" issue="LANG-659">EntityArrays typo: {"\u2122", "&amp;minus;"}, // minus sign, U+2212 ISOtech.</action>
180 <action type="fix" issue="LANG-658">Some Entitys like &amp;Ouml; are not matched properly against its ISO8859-1 representation.</action>
181 <action type="fix" issue="LANG-656">Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect.</action>
182 <action type="add" issue="LANG-655">Add StringUtils.defaultIfBlank().</action>
183 <action type="add" issue="LANG-653">Provide a very basic ConcurrentInitializer implementation.</action>
184 <action type="add" issue="LANG-609">Support lazy initialization using atomic variables.</action>
185 <action type="add" issue="LANG-482">Enhance StrSubstitutor to support nested ${var-${subvr}} expansion.</action>
186 <action type="add" issue="LANG-644">Provide documentation about the new concurrent package.</action>
187 <action type="fix" issue="LANG-629">Charset may not be threadsafe, because the HashSet is not synch.</action>
188 <action type="fix" issue="LANG-617">StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters.</action>
189 <action type="add" issue="LANG-614">StringUtils.endsWithAny method.</action>
190 <action type="add" issue="LANG-651">Add AnnotationUtils.</action>
191 <action type="add" issue="LANG-649">BooleanUtils.toBooleanObject to support single character input.</action>
192 <action type="fix" issue="LANG-645">FastDateFormat.format() outputs incorrect week of year because locale isn't respected.</action>
193 <action type="fix" issue="LANG-596">StrSubstitutor should also handle the default properties of a java.util.Properties class.</action>
194 <action type="fix" issue="LANG-643">Javadoc StringUtils.left() claims to throw on negative len, but doesn't.</action>
195 <action type="add" issue="LANG-640">Add normalizeSpace to StringUtils.</action>
196 <action type="fix" issue="LANG-638">NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in.</action>
197 <!-- 3.0 beta below here -->
198 <action>NOTE: The below were included in the Commons Lang 3.0-beta release.</action>
199 <action type="update" issues="LANG-510">Convert StringUtils API to take CharSequence.</action>
200 <action type="update">Push down WordUtils to "text" sub-package.</action>
201 <action type="add" issue="LANG-610">Extend exception handling in ConcurrentUtils to runtime exceptions.</action>
202 <action type="fix" issue="LANG-608">Some StringUtils methods should take an int character instead of char to use String API features.</action>
203 <action type="fix" issue="LANG-606">EqualsBuilder causes StackOverflowException.</action>
204 <action type="update" issue="LANG-605">DefaultExceptionContext overwrites values in recursive situations.</action>
205 <action type="fix" issue="LANG-602">ContextedRuntimeException no longer an 'unchecked' exception.</action>
206 <action type="add" issue="LANG-601">Add Builder Interface / Update Builders to Implement It.</action>
207 <action type="fix" issue="LANG-600">Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr).</action>
208 <action type="update" issue="LANG-599">ClassUtils.getClass(): Allow Dots as Inner Class Separators.</action>
209 <action type="add" issue="LANG-594">DateUtils equal &amp; compare functions up to most significant field.</action>
210 <action type="remove" issue="LANG-590">Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int).</action>
211 <action type="add" issue="LANG-588">Create a basic Pair&lt;L, R&gt; class.</action>
212 <action type="fix" issue="LANG-585">exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable.</action>
213 <action type="add" issue="LANG-582">Provide an implementation of the ThreadFactory interface.</action>
214 <action type="update" issue="LANG-579">Add new Validate methods.</action>
215 <action type="fix" issue="LANG-571">ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException.</action>
216 <action type="update" issue="LANG-570">Do the test cases really still require main() and suite() methods?.</action>
217 <action type="fix" issue="LANG-568">@SuppressWarnings("unchecked") is used too generally.</action>
218 <action type="fix" issue="LANG-564">Improve StrLookup API documentation.</action>
219 <action type="update" issue="LANG-563">Change Java package name.</action>
220 <action type="update" issue="LANG-562">Change Maven groupId.</action>
221 <action type="add" issue="LANG-560">New TimedSemaphore class.</action>
222 <action type="add" issue="LANG-559">Added validState validation method.</action>
223 <action type="add" issue="LANG-559">Added isAssignableFrom and isInstanceOf validation methods.</action>
224 <action type="add" issue="LANG-553">Add TypeUtils class to provide utility code for working with generic types.</action>
225 <action type="update" issue="LANG-551">Replace Range classes with generic version.</action>
226 <action type="update" issue="LANG-548">Use Iterable on API instead of Collection.</action>
227 <action type="add" issue="LANG-546">Add methods to Validate to check whether the index is valid for the array/list/string.</action>
228 <action type="add" issue="LANG-545">Add ability to create a Future for a constant.</action>
229 <action type="update" issue="LANG-541">Replace StringBuffer with StringBuilder.</action>
230 <action type="update" issue="LANG-540">Make NumericEntityEscaper immutable.</action>
231 <action type="update" issue="LANG-539">Compile commons.lang for CDC 1.1/Foundation 1.1.</action>
232 <action type="add" issue="LANG-537">Add ArrayUtils.toArray to create generic arrays.</action>
233 <action type="add" issue="LANG-533">Validate: support for validating blank strings.</action>
234 <action type="add" issue="LANG-529">Add a concurrent package.</action>
235 <action type="update" issue="LANG-528">Mutable classes should implement an appropriately typed Mutable interface.</action>
236 <action type="update" issue="LANG-513">Better EnumUtils.</action>
237 <action type="update" issue="LANG-507">StringEscapeUtils.unescapeJava should support \u+ notation.</action>
238 <action type="update" issue="LANG-505">Rewrite StringEscapeUtils.</action>
239 <action type="update" issue="LANG-504">bring ArrayUtils.isEmpty to the generics world.</action>
240 <action type="add" issue="LANG-501">Add support for background initialization.</action>
241 <action type="add" issue="LANG-499">Add support for the handling of ExecutionExceptions.</action>
242 <action type="add" issue="LANG-498">Add StringEscapeUtils.escapeText() methods.</action>
243 <action type="add" issue="LANG-497">Addition of ContextedException and ContextedRuntimeException.</action>
244 <action type="add" issue="LANG-496">A generic implementation of the Lazy initialization pattern.</action>
245 <action type="remove" issue="LANG-493">Remove code that does not hold enough value to remain.</action>
246 <action type="remove" issue="LANG-492">Remove code handled now by the JDK.</action>
247 <action type="add" issue="LANG-482">StrSubstitutor now supports substitution in variable names.</action>
248 <action type="fix" issue="LANG-481">Possible race-conditions in hashCode of the range classes.</action>
249 <action type="fix" issue="LANG-480">StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters.</action>
250 <action type="update" issue="LANG-479">Document where in SVN trunk is.</action>
251 <action type="fix" issue="LANG-478">StopWatch does not resist to system time changes.</action>
252 <action type="fix" issue="LANG-474">Fixes for thread safety.</action>
253 <action type="update" issue="LANG-458">Refactor Validate.java to eliminate code redundancy.</action>
254 <action type="fix" issue="LANG-448">Lower Ascii Characters don't get encoded by Entities.java.</action>
255 <action type="add" issue="LANG-444">StringUtils.emptyToNull.</action>
256 <action type="fix" issue="LANG-439">StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20).</action>
257 <action type="remove" issue="LANG-438">Remove @deprecateds.</action>
258 <action type="add" issue="LANG-435">Add ClassUtils.isAssignable() variants with autoboxing.</action>
259 <action type="update" issue="LANG-424">Improve Javadoc for StringUtils class.</action>
260 <action type="fix" issue="LANG-418">Javadoc incorrect for StringUtils.endsWithIgnoreCase.</action>
261 <action type="update" issue="LANG-396">Investigate for vararg usages.</action>
262 <action type="fix" issue="LANG-468">JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder).</action>
263 <action type="add" issue="LANG-386">LeftOf/RightOfNumber in Range convenience methods necessary.</action>
264 <action type="fix" issue="LANG-369">ExceptionUtils not thread-safe.</action>
265 <action type="add" issue="LANG-358">ObjectUtils.coalesce.</action>
266 <action type="update" issue="LANG-355">StrBuilder should implement CharSequence and Appendable.</action>
267 <action type="fix" issue="LANG-339">StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese, etc.</action>
268 <action type="update" issue="LANG-336">Finally start using generics.</action>
269 <action type="fix" issue="LANG-302">StrBuilder does not implement clone().</action>
270 <action type="update" issue="LANG-290">EnumUtils for JDK 5.0.</action>
271 <action type="add" issue="LANG-285">Wish : method unaccent.</action>
272 <action type="add" issue="LANG-276">MutableBigDecimal and MutableBigInteger.</action>
273 <action type="fix" issue="LANG-66">StringEscaper.escapeXml() escapes characters &gt; 0x7f.</action>
274 <action type="fix" issue="LANG-11">Depend on JDK 1.5+.</action>
275 </release>
276
277 <release version="2.6" date="2011-01-16" description="Bug Fixes/Enhancements for the 2.6 release (requires minimum of Java 1.3)">
278 <action type="update" issue="LANG-633">BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String).</action>
279 <action type="update" issue="LANG-599">ClassUtils: allow Dots as Inner Class Separators in getClass().</action>
280 <action type="add" issue="LANG-594">DateUtils: equal and compare functions up to most significant field.</action>
281 <action type="add" issue="LANG-632">DateUtils: provide a Date to Calendar convenience method.</action>
282 <action type="add" issue="LANG-576">ObjectUtils: add clone methods to ObjectUtils.</action>
283 <action type="add" issue="LANG-667">ObjectUtils: add a Null-safe compare() method.</action>
284 <action type="add" issue="LANG-670">ObjectUtils: add notEqual() method.</action>
285 <action type="add" issue="LANG-302">StrBuilder: implement clone() method.</action>
286 <action type="add" issue="LANG-640">StringUtils: add a normalizeSpace() method.</action>
287 <action type="add" issue="LANG-614">StringUtils: add endsWithAny() method.</action>
288 <action type="add" issue="LANG-655">StringUtils: add defaultIfBlank() method.</action>
289 <action type="add" issue="LANG-596">StrSubstitutor: add a replace(String, Properties) variant.</action>
290 <action type="add" issue="LANG-482">StrSubstitutor: support substitution in variable names.</action>
291 <action type="update" issue="LANG-669">Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue.</action>
292 <action type="fix" issue="LANG-629">CharSet: make the underlying set synchronized.</action>
293 <action type="fix" issue="LANG-635">CompareToBuilder: fix passing along compareTransients to the reflectionCompare method.</action>
294 <action type="fix" issue="LANG-636">ExtendedMessageFormat doesn't override equals(Object).</action>
295 <action type="fix" issue="LANG-645">FastDateFormat: fix to properly include the locale when formatting a Date.</action>
296 <action type="fix" issue="LANG-638">NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in.</action>
297 <action type="fix" issue="LANG-607">StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly.</action>
298 <action type="fix" issue="LANG-624">SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM.</action>
299 <action type="fix" issue="BEANUTILS-381">MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading.</action>
300 <action type="update" issue="LANG-600">Javadoc is incorrect for lastIndexOf() method.</action>
301 <action type="update" issue="LANG-628">Javadoc for HashCodeBuilder.append(boolean) does not match implementation.</action>
302 <action type="update" issue="LANG-643">Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't.</action>
303 <action type="update" issue="LANG-370">Javadoc - document thread safety.</action>
304 <action type="update" issue="LANG-623">Test for StringUtils replaceChars() icelandic characters.</action>
305 </release>
306
307 <release version="2.5" date="2010-02-25" description="">
308 <action type="add" issue="LANG-583">ArrayUtils - add isNotEmpty() methods.</action>
309 <action type="add" issue="LANG-534">ArrayUtils - add nullToEmpty() methods.</action>
310 <action type="add" issue="LANG-454">CharRange - provide an iterator that lets you walk the chars in the range.</action>
311 <action type="add" issue="LANG-514">CharRange - add more readable static builder methods.</action>
312 <action type="add">ClassUtils - new isAssignable() methods with autoboxing.</action>
313 <action type="add" issue="LANG-535">ClassUtils - add support to getShortClassName and getPackageName for arrays.</action>
314 <action type="add" issue="LANG-434">DateUtils - add ceiling() method.</action>
315 <action type="add" issue="LANG-486">DateUtils - add parseDateStrictly() method.</action>
316 <action type="add" issue="LANG-466">EqualsBuilder - add reset() method.</action>
317 <action type="add" issue="LANG-461">NumberUtils - add toByte() and toShort() methods.</action>
318 <action type="add" issue="LANG-522">Mutable numbers - add string constructors.</action>
319 <action type="add">MutableBoolean - add toBoolean(), isTrue() and isFalse() methods.</action>
320 <action type="add" issue="LANG-422">StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty.</action>
321 <action type="add" issue="LANG-555">SystemUtils - add IS_OS_WINDOWS_7 constant.</action>
322 <action type="add" issue="LANG-554">SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7.</action>
323 <action type="add" issue="LANG-405">StringUtils - add abbreviateMiddle() method.</action>
324 <action type="add" issue="LANG-569">StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods.</action>
325 <action type="add" issue="LANG-471">StringUtils - add isAllUpperCase() and isAllLowerCase() methods.</action>
326 <action type="add" issue="LANG-469">StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method.</action>
327 <action type="add" issue="LANG-348">StringUtils - add repeat() method.</action>
328 <action type="add" issue="LANG-445">StringUtils - add startsWithAny() method.</action>
329 <action type="add" issue="LANG-430">StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods.</action>
330 <action type="add" issue="LANG-416">New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils.</action>
331 <action type="fix" issue="LANG-567">ArrayUtils - addAll() does not handle mixed types very well.</action>
332 <action type="fix" issue="LANG-494">CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread.</action>
333 <action type="fix" issue="LANG-500">ClassUtils - improving performance of getAllInterfaces.</action>
334 <action type="fix" issue="LANG-587">ClassUtils - toClass() throws NullPointerException on null array element.</action>
335 <action type="fix" issue="LANG-530">DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat.</action>
336 <action type="fix" issue="LANG-440">DateUtils - round() doesn't work correct for Calendar.AM_PM.</action>
337 <action type="fix" issue="LANG-443">DateUtils - improve tests.</action>
338 <action type="fix" issue="LANG-204">Entities - multithreaded initialization.</action>
339 <action type="fix" issue="LANG-506">Entities - missing final modifiers; thread-safety issues.</action>
340 <action type="fix" issue="LANG-76">EnumUtils - getEnum() doesn't work well in 1.5+.</action>
341 <action type="fix" issue="LANG-584">ExceptionUtils - use immutable lock target.</action>
342 <action type="fix" issue="LANG-477">ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes.</action>
343 <action type="fix" issue="LANG-538">FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state.</action>
344 <action type="fix" issue="LANG-547">FastDateFormat - Remove unused field.</action>
345 <action type="fix" issue="LANG-511">LocaleUtils - Initialization of available locales in LocaleUtils can be deferred.</action>
346 <action type="fix" issue="LANG-457">NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in.</action>
347 <action type="fix" issue="LANG-521">NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'.</action>
348 <action type="fix" issue="LANG-432">StringUtils - improve handling of case-insensitive Strings.</action>
349 <action type="fix" issue="LANG-552">StringUtils - replaceEach() no longer NPEs when null appears in the last String[].</action>
350 <action type="fix" issue="LANG-460">StringUtils - correct Javadoc for startsWith() and startsWithIgnoreCase().</action>
351 <action type="fix" issue="LANG-421">StringEscapeUtils - escapeJava() escapes '/' characters.</action>
352 <action type="fix" issue="LANG-450">StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null.</action>
353 <action type="fix" issue="LANG-419">WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length.</action>
354 <action type="fix" issue="LANG-523">StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity.</action>
355 <action type="fix" issue="LANG-575">Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List.</action>
356 <action type="fix" issue="LANG-467">EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder.</action>
357 <action type="fix" issue="LANG-574">HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks.</action>
358 <action type="fix" issue="LANG-520">HashCodeBuilder - Changing the hashCode() method to return toHashCode().</action>
359 <action type="fix" issue="LANG-459">HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes.</action>
360 <action type="fix" issue="LANG-586">HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments.</action>
361 <action type="fix" issue="LANG-487">ToStringBuilder - make default style thread-safe.</action>
362 <action type="fix" issue="LANG-472">RandomUtils - nextLong() always produces even numbers.</action>
363 <action type="fix" issue="LANG-592">RandomUtils - RandomUtils tests are failing frequently.</action>
364 </release>
365
366 <release version="2.4" date="2008-03-18" description="">
367 <action type="add" issue="LANG-322">ClassUtils.getShortClassName(String) inefficient.</action>
368 <action type="add" issue="LANG-269">Shouldn't Commons Lang's StringUtils have a "common" string method?.</action>
369 <action type="fix" issue="LANG-368">FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change.</action>
370 <action type="add" issue="LANG-402">OSGi-ify Lang.</action>
371 <action type="fix" issue="LANG-412">StrBuilder appendFixedWidth does not handle nulls.</action>
372 <action type="fix" issue="LANG-380">infinite loop in Fraction.reduce when numerator == 0.</action>
373 <action type="fix" issue="LANG-367">FastDateFormat thread safety.</action>
374 <action type="add" issue="LANG-298">ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array.</action>
375 <action type="fix" issue="LANG-328">LocaleUtils.toLocale() rejects strings with only language+variant.</action>
376 <action type="fix" issue="LANG-334">Enum is not thread-safe.</action>
377 <action type="fix" issue="LANG-365">BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException.</action>
378 <action type="add" issue="LANG-333">ArrayUtils.toClass.</action>
379 <action type="fix" issue="LANG-360">Why does appendIdentityToString return null?.</action>
380 <action type="fix" issue="LANG-381">NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN.</action>
381 <action type="fix" issue="LANG-346">Dates.round() behaves incorrectly for minutes and seconds.</action>
382 <action type="add" issue="LANG-407">StringUtils.length(String) returns null-safe length.</action>
383 <action type="add" issue="LANG-180">adding a StringUtils.replace method that takes an array or List of replacement strings.</action>
384 <action type="add" issue="LANG-383">Adding functionality to DateUtils to allow direct setting of various fields.</action>
385 <action type="add" issue="LANG-374">Add escaping for CSV columns to StringEscapeUtils.</action>
386 <action type="add" issue="LANG-326">StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods.</action>
387 <action type="add" issue="LANG-351">Extension to ClassUtils: Obtain the primitive class from a wrapper.</action>
388 <action type="fix" issue="LANG-399">Javadoc bugs - cannot find object.</action>
389 <action type="add" issue="LANG-345">Optimize HashCodeBuilder.append(Object).</action>
390 <action type="fix" issue="LANG-385">http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete.</action>
391 <action type="fix" issue="LANG-410">Ambiguous / confusing names in StringUtils replace* methods.</action>
392 <action type="add" issue="LANG-257">Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils.</action>
393 <action type="add" issue="LANG-356">Add getStartTime to StopWatch.</action>
394 <action type="add" issue="LANG-377">Perhaps add containsAny() methods?.</action>
395 <action type="fix" issue="LANG-353">Javadoc Example for EqualsBuilder is questionable.</action>
396 <action type="fix" issue="LANG-393">EqualsBuilder don't compare BigDecimals correctly.</action>
397 <action type="add" issue="LANG-192">Split camel case strings.</action>
398 <action type="add" issue="LANG-404">Add Calendar flavour format methods to DateFormatUtils.</action>
399 <action type="add" issue="LANG-379">Calculating A date fragment in any time-unit.</action>
400 <action type="add" issue="LANG-413">Memory usage improvement for StringUtils#getLevenshteinDistance().</action>
401 <action type="add" issue="LANG-362">Add ExtendedMessageFormat to org.apache.commons.lang.text.</action>
402 <action type="fix" issue="LANG-363">StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly.</action>
403 <action type="add" issue="LANG-321">Add toArray() method to IntRange and LongRange classes.</action>
404 <action type="add" issue="LANG-375">add SystemUtils.IS_OS_WINDOWS_VISTA field.</action>
405 <action type="add" issue="LANG-329">Pointless synchronized in ThreadLocal.initialValue should be removed.</action>
406 <action type="add" issue="LANG-371">ToStringStyle Javadoc should show examples of styles.</action>
407 <action type="fix" issue="LANG-364">Documentation bug for ignoreEmptyTokens accessors in StrTokenizer.</action>
408 <action type="fix" issue="LANG-361">BooleanUtils toBooleanObject Javadoc does not match implementation.</action>
409 <action type="add" issue="LANG-338">truncateNicely method which avoids truncating in the middle of a word.</action>
410 </release>
411
412 <release version="2.3" date="2007-02-13" description="">
413 <action type="fix" issue="LANG-262">Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions.</action>
414 <action type="add" issue="LANG-289">NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing.</action>
415 <action type="add" issue="LANG-291">Null-safe comparison methods for finding most recent / least recent dates.</action>
416 <action type="fix" issue="LANG-315">StopWatch: suspend() acts as split(), if followed by stop().</action>
417 <action type="fix" issue="LANG-294">StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException.</action>
418 <action type="fix" issue="LANG-299">Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException.</action>
419 <action type="fix" issue="LANG-69"> ToStringBuilder throws StackOverflowError when an Object cycle exists.</action>
420 <action type="add" issue="LANG-282">Create more tests to test out the +=31 replacement code in DurationFormatUtils.</action>
421 <action type="fix" issue="LANG-295">StrBuilder contains usages of thisBuf.length when they should use size.</action>
422 <action type="add" issue="LANG-258">Enum Javadoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui.</action>
423 <action type="fix" issue="LANG-313">Wrong behavior of Entities.unescape.</action>
424 <action type="fix" issue="LANG-300">NumberUtils.createNumber throws NumberFormatException for one digit long.</action>
425 <action type="fix" issue="LANG-304">NullPointerException in isAvailableLocale(Locale).</action>
426 <action type="fix" issue="LANG-303">FastDateFormat.mRules is not transient or serializable.</action>
427 <action type="add" issue="LANG-268">StringUtils.join should allow you to pass a range for it (so it only joins a part of the array).</action>
428 <action type="fix" issue="LANG-102">Refactor Entities methods.</action>
429 <action type="fix" issue="LANG-314">Tests fail to pass when building with Maven 2.</action>
430 <action type="fix" issue="LANG-281">DurationFormatUtils returns wrong result.</action>
431 <action type="fix" issue="LANG-292">unescapeXml("&amp;12345678;") should be "&amp;12345678;".</action>
432 <action type="add" issue="LANG-287">Optimize StringEscapeUtils.unescapeXml(String).</action>
433 <action type="add" issue="LANG-310">BooleanUtils isNotTrue/isNotFalse.</action>
434 <action type="add" issue="LANG-306">Extra StrBuilder methods.</action>
435 <action type="add" issue="LANG-275">Add a pair of StringUtils.substringsBetween;String[] methods.</action>
436 <action type="fix" issue="LANG-279">HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle.</action>
437 <action type="add" issue="LANG-266">Wish for StringUtils.join(Collection, *).</action>
438 </release>
439
440 <release version="2.2" date="2006-10-04" description="">
441 <action type="fix" issue="LANG-45">StrBuilderTest#testReplaceStringString fails.</action>
442 <action type="fix" issue="LANG-42">EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null.</action>
443 <action type="fix" issue="LANG-286">Serialization - not backwards compatible.</action>
444 <action type="fix" issue="LANG-50"> Replace Clover with Cobertura.</action>
445 <action type="fix" issue="LANG-259">ValuedEnum.compareTo(Object other) not typesafe - it easily could be...</action>
446 <action type="fix" issue="LANG-271">LocaleUtils test fails under Mustang.</action>
447 <action type="fix" issue="LANG-2">Javadoc example for StringUtils.splitByWholeSeparator incorrect.</action>
448 <action type="fix" issue="LANG-3">PADDING array in StringUtils overflows on '\uffff'.</action>
449 <action type="fix" issue="LANG-10">ClassUtils.primitiveToWrapper and Void.</action>
450 <action type="fix" issue="LANG-37">unit test for org.apache.commons.lang.text.StrBuilder.</action>
451 <action type="fix" issue="LANG-59">DateUtils.truncate method is buggy when dealing with DST switching hours.</action>
452 <action type="fix" issue="LANG-100">RandomStringUtils.random() family of methods create invalid Unicode sequences.</action>
453 <action type="fix" issue="LANG-106">StringUtils#getLevenshteinDistance() performance is sub-optimal.</action>
454 <action type="fix" issue="LANG-112">Wrong length check in StrTokenizer.StringMatcher.</action>
455 <action type="fix" issue="LANG-105">ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable.</action>
456 <action type="fix" issue="LANG-117">FastDateFormat: wrong format for date "01.01.1000".</action>
457 <action type="fix" issue="LANG-123">Unclear Javadoc for DateUtils.iterator().</action>
458 <action type="fix" issue="LANG-130">Memory "leak" in StringUtils.</action>
459 <action type="add" issue="LANG-260">StringEscapeUtils should expose escape*() methods taking Writer argument.</action>
460 <action type="fix" issue="LANG-141">Fraction.toProperString() returns -1/1 for -1.</action>
461 <action type="fix" issue="LANG-152">DurationFormatUtils.formatDurationWords "11 &lt;unit&gt;s" gets converted to "11 &lt;unit&gt;".</action>
462 <action type="fix" issue="LANG-148">Performance modifications on StringUtils.replace.</action>
463 <action type="fix" issue="LANG-150">StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand.</action>
464 <action type="fix" issue="LANG-140">DurationFormatUtils.formatPeriod() returns the wrong result.</action>
465 <action type="add" issue="LANG-186">Request for MutableBoolean implementation.</action>
466 <action type="add" issue="LANG-198">New method for EqualsBuilder.</action>
467 <action type="add" issue="LANG-212">New ExceptionUtils method setCause().</action>
468 <action type="add" issue="LANG-217">Add Mutable&lt;Type&gt; to&lt;Type&gt;() methods.</action>
469 <action type="add" issue="LANG-216">Provides a Class.getPublicMethod which returns public invocable Method.</action>
470 <action type="add" issue="LANG-226">Using ReflectionToStringBuilder and excluding secure fields.</action>
471 <action type="add" issue="LANG-194">add generic add method to DateUtils.</action>
472 <action type="add" issue="LANG-220">Tokenizer Enhancements: reset input string, static CSV/TSV factories.</action>
473 <action type="add" issue="LANG-242">Trivial cleanup of Javadoc in various files.</action>
474 <action type="add" issue="LANG-246">CompositeFormat.</action>
475 <action type="add" issue="LANG-250">Performance boost for RandomStringUtils.</action>
476 <action type="add" issue="LANG-254">Enhanced Class.forName version.</action>
477 <action type="add" issue="LANG-263">Add StringUtils.containsIgnoreCase(...).</action>
478 <action type="add" issue="LANG-267">Support char array converters on ArrayUtils.</action>
479 <action type="fix" issue="LANG-25">DurationFormatUtils.formatDurationISO() Javadoc is missing T in duration string between date and time part.</action>
480 <action type="fix" issue="LANG-272">Minor build and checkstyle changes.</action>
481 <action type="fix" issue="LANG-277">Javadoc errors on StringUtils.splitPreserveAllTokens(String, char).</action>
482 <action type="fix" issue="LANG-122">EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &amp;apos;.</action>
483 <action type="add" issue="LANG-161">Add methods and tests to StrBuilder.</action>
484 <action type="add" issue="LANG-162">replace() length calculation improvement.</action>
485 <action type="add" issue="LANG-166">New interpolation features.</action>
486 <action type="add" issue="LANG-169">Implementation of escape/unescapeHtml methods with Writer.</action>
487 <action type="add" issue="LANG-176">CompareToBuilder excludeFields for reflection method.</action>
488 <action type="add" issue="LANG-159">Add WordUtils.getInitials(String).</action>
489 <action type="fix" issue="LANG-261">Error in an example in the Javadoc of the StringUtils.splitPreserveAllTokens() method.</action>
490 <action type="fix" issue="LANG-264">ToStringBuilder/HashCodeBuilder Javadoc code examples.</action>
491 <action type="fix" issue="LANG-265">Cannot build tests from latest SVN.</action>
492 <action type="add" issue="LANG-270">minor Javadoc improvements for StringUtils.stripXxx() methods.</action>
493 <action type="fix" issue="LANG-278">Javadoc for StringUtils.removeEnd is incorrect.</action>
494 <action type="fix" issue="LANG-127">Minor tweak to fix of bug # 26616.</action>
495 </release>
496
497 <release version="2.1" date="2005-06-13" description="">
498 <action type="fix" issue="LANG-103">make optional parameters in FastDateFormat really optional.</action>
499 <action type="fix" issue="LANG-149">Nestable.indexOfThrowable(Class) uses Class.equals() to match.</action>
500 <action type="fix" issue="LANG-30">buffer under/overrun on Strings.strip, stripStart &amp; stripEnd.</action>
501 <action type="fix" issue="LANG-19">ToStringStyle.setArrayEnd(String) doesn't replace null with empty string.</action>
502 <action type="fix" issue="LANG-80">New class proposal: CharacterEncoding.</action>
503 <action type="fix" issue="LANG-43">SystemUtils fails init on HP-UX.</action>
504 <action type="fix" issue="LANG-134">Javadoc - 'four basic XML entities' should be 5 (apos is missing).</action>
505 <action type="fix" issue="LANG-156">o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0.</action>
506 <action type="fix" issue="LANG-131">StringEscapeUtils.unescapeHtml() doesn't handle an empty entity.</action>
507 <action type="fix" issue="LANG-6">EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class.</action>
508 <action type="fix" issue="LANG-33">Method enums.Enum.equals(Object o) doesn't work correctly.</action>
509 <action type="fix" issue="LANG-31">ExceptionUtils.addCauseMethodName(String) does not check for duplicates.</action>
510 <action type="fix" issue="LANG-136">Make StopWatch validate state transitions.</action>
511 <action type="fix" issue="LANG-124">enum package is not compatible with 1.5 jdk.</action>
512 <action type="fix" issue="LANG-128">WordUtils capitalizeFully() throws a null pointer exception.</action>
513 <action type="fix" issue="LANG-138">ValuedEnum.</action>
514 <action type="fix" issue="LANG-133">parseDate class from HttpClient's DateParser class.</action>
515 <action type="fix" issue="LANG-62">ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension.</action>
516 <action type="fix" issue="LANG-57">ClassCastException in Enum.equals(Object).</action>
517 <action type="fix" issue="LANG-107">FastDateFormat year bug.</action>
518 <action type="fix" issue="LANG-77">unbalanced ReflectionToStringBuilder.</action>
519 <action type="fix" issue="LANG-86">FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation.</action>
520 <action type="fix" issue="LANG-79">ReflectionToStringBuilder.toString(null) throws exception by design.</action>
521 <action type="fix" issue="LANG-126">Make ClassUtils methods null-safe and not throw an IAE.</action>
522 <action type="fix" issue="LANG-5">StringUtils.split ignores empty items.</action>
523 <action type="fix" issue="LANG-144">EqualsBuilder.append(Object[], Object[]) throws NPE.</action>
524 <action type="fix" issue="LANG-74">ArrayUtils.addAll doesn't always return new array.</action>
525 <action type="fix" issue="LANG-81">Enum.equals does not handle different class loaders.</action>
526 <action type="fix" issue="LANG-27">Add SystemUtils.AWT_TOOLKIT and others.</action>
527 <action type="fix" issue="LANG-14">Throwable cause for NotImplementedException.</action>
528 <action type="fix" issue="LANG-28">ClassUtils.primitivesToWrappers method.</action>
529 <action type="fix" issue="LANG-120">public static boolean DateUtils.equals(Date dt1, Date dt2) ?.</action>
530 <action type="fix" issue="LANG-7">Documentation error in StringUtils.replace.</action>
531 <action type="fix" issue="LANG-125">DateUtils constants should be long.</action>
532 <action type="fix" issue="LANG-13">DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'.</action>
533 <action type="fix" issue="LANG-118">StringEscapeUtils.unescapeHtml() doesn't handle hex entities.</action>
534 <action type="fix" issue="LANG-99">new StringUtils.replaceChars behaves differently from old CharSetUtils.translate.</action>
535 <action type="fix" issue="LANG-41">last substring returned by StringUtils.split( String, String, int ) is too long.</action>
536 <action type="fix" issue="LANG-119">Can't subclass EqualsBuilder because isEquals is private.</action>
537 <action type="fix" issue="LANG-158">new StringUtils.split methods that split on the whole separator string.</action>
538 <action type="add" issue="LANG-172">New method for converting a primitive Class to its corresponding wrapper Class.</action>
539 <action type="add" issue="LANG-222">Add convenience format(long) methods to FastDateFormat.</action>
540 <action type="fix" issue="LANG-116">Enum's outer class may not be loaded for EnumUtils.</action>
541 <action type="add" issue="LANG-219">WordUtils.capitalizeFully(String str) should take a delimiter.</action>
542 <action type="add" issue="LANG-183">Make Javadoc crosslinking configurable.</action>
543 <action type="fix" issue="LANG-82">Minor Javadoc fixes for StringUtils.contains(String, String).</action>
544 <action type="fix" issue="LANG-32">Error in Javadoc for StringUtils.chomp(String, String).</action>
545 <action type="fix" issue="LANG-95">StringUtils.defaultString: Documentation error.</action>
546 <action type="add" issue="LANG-233">Add hashCode-support to class ObjectUtils.</action>
547 <action type="add" issue="LANG-202">add another "known method" to ExceptionUtils.</action>
548 <action type="add" issue="LANG-235">Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES.</action>
549 <action type="fix" issue="LANG-24">DateUtils.truncate oddity at the far end of the Date spectrum.</action>
550 <action type="add" issue="LANG-232">add getLength() method to ArrayUtils.</action>
551 <action type="add" issue="LANG-171">Validate.java: fixes comment skew, removes unused loop counter.</action>
552 <action type="add" issue="LANG-179">StringUtils.isAsciiPrintable().</action>
553 <action type="add" issue="LANG-167">ExceptionUtils: new getCause() methodname (for tomcat-exception).</action>
554 <action type="fix" issue="LANG-85">fixes 75 typos.</action>
555 <action type="add" issue="LANG-230">mutable numbers.</action>
556 <action type="add" issue="LANG-191">Javadoc fixes for ClassUtils.</action>
557 <action type="add" issue="LANG-184">Add StringUtils.nIndexOf?.</action>
558 <action type="fix" issue="LANG-135">Javadoc fixes for CharSetUtils.</action>
559 <action type="fix" issue="LANG-154">Remove redundant check for null separator in StringUtils#join.</action>
560 <action type="add" issue="LANG-247">Class and Package Comparators for ClassUtils.</action>
561 <action type="add" issue="LANG-256">add remove methods to ArrayUtils.</action>
562 <action type="add" issue="LANG-185">WordUtils capitalize improvement.</action>
563 <action type="add" issue="LANG-173">add isEmpty method to ArrayUtils.</action>
564 <action type="add" issue="LANG-168">lang.math.Fraction class deficiencies.</action>
565 <action type="add" issue="LANG-207">Add methods to ArrayUtils: add at end and insert-like ops.</action>
566 <action type="add" issue="LANG-239">Add SystemUtils methods for directory properties.</action>
567 <action type="add" issue="LANG-189">Add method that validates Collection elements are a certain type.</action>
568 <action type="add" issue="LANG-224">elapsed time formatting utility method.</action>
569 </release>
570
571 <release version="2.0" date="2003-09-02" description="">
572 <action type="fix" issue="LANG-20">Infinite loop in ToStringBuilder.reflectionToString for inner classes.</action>
573 <action type="fix" issue="LANG-75">NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08.</action>
574 <action type="fix" issue="LANG-38">Rationalize StringUtils slice functions.</action>
575 <action type="fix" issue="LANG-53">SystemUtils.IS_OS_OS2 Javadoc is wrong.</action>
576 <action type="fix" issue="LANG-142">A small, but important Javadoc fix for Fraction proper whole and numerator.</action>
577 <action type="fix" issue="LANG-70">Adding tolerance to double[] search methods in ArrayUtils.</action>
578 <action type="fix" issue="LANG-9">lang.builder classes Javadoc edits (mostly typo fixes).</action>
579 <action type="fix" issue="LANG-63">StringUtils Javadoc and test enhancements.</action>
580 <action type="fix" issue="LANG-132">SystemUtils.IS_OS_*, IS_JAVA_* are always false.</action>
581 <action type="fix" issue="LANG-143">Improve util.Validate tests.</action>
582 <action type="fix" issue="LANG-155">maven-beta10 checkstyle problem.</action>
583 <action type="fix" issue="LANG-147">StringUtils.chopNewLine - StringIndexOutOfBoundsException.</action>
584 <action type="fix" issue="LANG-73">ToStringBuilder doesn't work well in subclasses.</action>
585 <action type="fix" issue="LANG-48">static option for reversing the stacktrace.</action>
586 <action type="fix" issue="LANG-87">NullPointerException in CompareToBuilder.</action>
587 <action type="fix" issue="LANG-84">RandomStringUtils.randomAlpha methods omit 'z'.</action>
588 <action type="fix" issue="LANG-129">test.time fails in Japanese (non-us) locale.</action>
589 <action type="fix" issue="LANG-94">NumberUtils.isNumber allows illegal trailing characters.</action>
590 <action type="fix" issue="LANG-137">Improve Javadoc and overflow behavior of Fraction.</action>
591 <action type="fix" issue="LANG-55">RandomStringUtils infloops with length &gt; 1.</action>
592 <action type="fix" issue="LANG-47">test.lang fails if compiled with non iso-8859-1 locales.</action>
593 <action type="fix" issue="LANG-113">SystemUtils does not play nice in an Applet.</action>
594 <action type="fix" issue="LANG-111">time unit tests fail on Sundays.</action>
595 <action type="fix" issue="LANG-90">java.lang.ExceptionInInitializerError thrown by JVMRandom constructor.</action>
596 <action type="fix" issue="LANG-78">StringUtils.chomp does not match Perl.</action>
597 <action type="fix" issue="LANG-36">patch and test case fixing problem with RandomStringUtils.random().</action>
598 <action type="fix" issue="LANG-151">General case: infinite loop: ToStringBuilder.reflectionToString.</action>
599 <action type="fix" issue="LANG-35">Should ToStringBuilder.reflectionToString handle arrays?.</action>
600 <action type="fix" issue="LANG-83">EnumUtils nit: The import java.io.Serializable is never used.</action>
601 <action type="fix" issue="LANG-12">Example in Javadoc for ToStringBuilder wrong for append.</action>
602 <action type="fix" issue="LANG-110">Added class hierarchy support to HashCodeBuilder.reflectionHashCode().</action>
603 <action type="fix" issue="LANG-71">ExceptionUtils new methods.</action>
604 <action type="fix" issue="LANG-15">Infinite loop in StringUtils.replace(text, repl, with) + FIX.</action>
605 <action type="fix" issue="LANG-93">StackOverflow due to ToStringBuilder.</action>
606 <action type="fix" issue="LANG-39">No Javadoc for NestableDelegate.</action>
607 <action type="fix" issue="LANG-49">Specify initial size for Enum's HashMap.</action>
608 <action type="fix" issue="LANG-146">Enum does not support inner sub-classes.</action>
609 <action type="fix" issue="LANG-157">Removed compile warning in ObjectUtils.</action>
610 <action type="fix" issue="LANG-96">SystemUtils.IS_JAVA_1_5 Javadoc is wrong.</action>
611 <action type="fix" issue="LANG-16">NumberRange inaccurate for Long, etc.</action>
612 <action type="fix" issue="LANG-4">Hierarchy support in ToStringBuilder.reflectionToString().</action>
613 <action type="fix" issue="LANG-56">StringUtils.countMatches loops forever if substring empty.</action>
614 <action type="add" issue="LANG-209">Javadoc fixes (remove @links to non-public identifiers).</action>
615 <action type="add" issue="LANG-210">Add Javadoc examples and tests for StringUtils.</action>
616 <action type="add" issue="LANG-170">Make NumberUtils null handling consistent.</action>
617 <action type="fix" issue="LANG-145">Unused field 'startFinal' in DateIterator.</action>
618 <action type="add" issue="LANG-214">reduce object creation in ToStringBuilder.</action>
619 <action type="add" issue="LANG-228">Improved tests, Javadoc for CharSetUtils, StringEscapeUtils.</action>
620 <action type="add" issue="LANG-252">NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject.</action>
621 <action type="add" issue="LANG-208">Javadoc, tests improvements for CharSet, CharSetUtils.</action>
622 <action type="add" issue="LANG-205">StringUtil enhancement.</action>
623 <action type="add" issue="LANG-164">Javadoc nit.</action>
624 <action type="add" issue="LANG-206">Additional Lang Method Suggestions.</action>
625 <action type="add" issue="LANG-178">Make NestableDelegate methods public instead of package private.</action>
626 <action type="add" issue="LANG-174">Missing @since tags.</action>
627 <action type="add" issue="LANG-245">Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder.</action>
628 <action type="fix" issue="LANG-51">Typo in documentation.</action>
629 <action type="fix" issue="LANG-1">Patch for Javadoc.</action>
630 <action type="add" issue="LANG-244">Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!.</action>
631 <action type="add" issue="LANG-231">Resurrect the WordWrapUtils from commons-sandbox/utils.</action>
632 <action type="fix" issue="LANG-139">EnumTest fails on Linux Sun JDK 1.3.0.</action>
633 <action type="add" issue="LANG-234">What to do with FastDateFormat unused private constructors.</action>
634 <action type="add" issue="LANG-240">Added class hierarchy support to CompareToBuilder.reflectionCompare().</action>
635 <action type="add" issue="LANG-190">Removed compile warning in FastDateFormat.</action>
636 <action type="fix" issue="LANG-97">typo in the Javadoc example code.</action>
637 <action type="add" issue="LANG-249">MethodUtils: Removed unused code/unused local vars.</action>
638 <action type="add" issue="LANG-237">Hierarchy support in EqualsBuilder.reflectionEquals().</action>
639 <action type="fix" issue="LANG-91">Javadoc Errata.</action>
640 <action type="add" issue="LANG-215">ArrayUtils.contains().</action>
641 <action type="add" issue="LANG-221">More flexibility for getRootCause in ExceptionUtils.</action>
642 </release>
643
644 <release version="1.0.1" date="2002-11-25" description="Quick bugfix to 1.0">
645 <action type="fix">NumberRange.getMaximum returns minimum.</action>
646 <action type="fix">Enum constructor validations.</action>
647 <action type="fix">NestableException/Delegate is not serializable.</action>
648 <action type="fix">split using null and max less than actual token count adds "null".</action>
649 <action type="add">ExceptionUtils cannot handle J2EE-Exception in a default way.</action>
650 </release>
651
652 <release version="1.0" date="2002-10-04" description="First release of Commons Lang">
653 </release>
654
655 </body>
656 </document>
0 ## Licensed to the Apache Software Foundation (ASF) under one
1 ## or more contributor license agreements. See the NOTICE file
2 ## distributed with this work for additional information
3 ## regarding copyright ownership. The ASF licenses this file
4 ## to you under the Apache License, Version 2.0 (the
5 ## "License"); you may not use this file except in compliance
6 ## with the License. You may obtain a copy of the License at
7 ##
8 ## http://www.apache.org/licenses/LICENSE-2.0
9 ##
10 ## Unless required by applicable law or agreed to in writing,
11 ## software distributed under the License is distributed on an
12 ## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
13 ## KIND, either express or implied. See the License for the
14 ## specific language governing permissions and limitations
15 ## under the License.
16 ##
17 Apache ${project.name}
18 Version ${version}
19 Release Notes
20
21
22 INTRODUCTION:
23
24 This document contains the release notes for the ${version} version of Apache Commons Lang.
25 Commons Lang is a set of utility functions and reusable components that should be of use in any
26 Java environment.
27
28 Lang 3.0 and onwards now targets Java 5.0, making use of features that arrived with Java 5.0 such as generics,
29 variable arguments, autoboxing, concurrency and formatted output.
30
31 For the advice on upgrading from 2.x to 3.x, see the following page:
32
33 http://commons.apache.org/lang/article3_0.html
34
35 $introduction.replaceAll("(?<!\015)\012", "
36 ").replaceAll("(?m)^ +","")
37
38 ## N.B. the available variables are described here:
39 ## http://maven.apache.org/plugins/maven-changes-plugin/examples/using-a-custom-announcement-template.html
40 ##
41 ## Hack to improve layout: replace all pairs of spaces with a single new-line
42 $release.description.replaceAll(" ", "
43 ")
44
45 ## set up indent sizes. Only change indent1
46 #set($props=${project.properties})
47 #set($jiralen=$props.get("commons.jira.id").length())
48 ## indent1 = POOL-nnnn:
49 #set($blanklen=$jiralen+6)## +6 for "-nnnn:"
50 ## must be at least as long as the longest JIRA id
51 #set($blanks=" ")
52 #set($indent1=$blanks.substring(0,$blanklen))
53 ## indent2 allows for issue wrapper
54 #set($indent2="$indent1 ")
55 ##
56 #macro ( processaction )
57 ## Use replaceAll to fix up LF-only line ends on Windows.
58 #set($action=$actionItem.getAction().replaceAll("\n","
59 "))
60 ## Fix up indentation for multi-line action descriptions
61 #set($action=$action.replaceAll("(?m)^ +",$indent2))
62 #if ($actionItem.getIssue())
63 #set($issue="$actionItem.getIssue():")
64 ## Pad shorter issue numbers
65 #if ($issue.length() < $indent1.length())#set ($issue="$issue ")#end
66 #if ($issue.length() < $indent1.length())#set ($issue="$issue ")#end
67 #if ($issue.length() < $indent1.length())#set ($issue="$issue ")#end
68 #else
69 #set($issue=$indent1)
70 #end
71 #if ($actionItem.getDueTo())
72 #set($dueto=" Thanks to $actionItem.getDueTo().")
73 #else
74 #set($dueto="")
75 #end
76 o $issue ${action}$dueto
77 #set($action="")
78 #set($issue="")
79 #set($dueto="")
80 #end
81 ##
82 #if ($release.getActions().size() == 0)
83 No changes defined in this version.
84 #else
85 Changes in this version include:
86
87 #if ($release.getActions('add').size() !=0)
88 New features:
89 #foreach($actionItem in $release.getActions('add'))
90 #processaction()
91 #end
92 #end
93
94 #if ($release.getActions('fix').size() !=0)
95 Fixed Bugs:
96 #foreach($actionItem in $release.getActions('fix'))
97 #processaction()
98 #end
99 #end
100
101 #if ($release.getActions('update').size() !=0)
102 Changes:
103 #foreach($actionItem in $release.getActions('update'))
104 #processaction()
105 #end
106 #end
107
108 #if ($release.getActions('remove').size() !=0)
109 Removed:
110 #foreach($actionItem in $release.getActions('remove'))
111 #processaction()
112 #end
113 #end
114 ## End of main loop
115 #end
116
117 Historical list of changes: ${project.url}changes-report.html
118
119 For complete information on ${project.name}, including instructions on how to submit bug reports,
120 patches, or suggestions for improvement, see the Apache ${project.name} website:
121
122 ${project.url}
4040 * <p>#ThreadSafe#</p>
4141 *
4242 * @since 3.0
43 * @version $Id: AnnotationUtils.java 1083850 2011-03-21 15:59:10Z mbenson $
43 * @version $Id: AnnotationUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
4444 */
4545 public class AnnotationUtils {
4646
6868 * {@inheritDoc}
6969 */
7070 @Override
71 protected String getShortClassName(java.lang.Class<?> cls) {
71 protected String getShortClassName(final java.lang.Class<?> cls) {
7272 Class<? extends Annotation> annotationType = null;
73 for (Class<?> iface : ClassUtils.getAllInterfaces(cls)) {
73 for (final Class<?> iface : ClassUtils.getAllInterfaces(cls)) {
7474 if (Annotation.class.isAssignableFrom(iface)) {
75 @SuppressWarnings("unchecked")
76 //because we just checked the assignability
75 @SuppressWarnings("unchecked") // OK because we just checked the assignability
76 final
7777 Class<? extends Annotation> found = (Class<? extends Annotation>) iface;
7878 annotationType = found;
7979 break;
8787 * {@inheritDoc}
8888 */
8989 @Override
90 protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
90 protected void appendDetail(final StringBuffer buffer, final String fieldName, Object value) {
9191 if (value instanceof Annotation) {
9292 value = AnnotationUtils.toString((Annotation) value);
9393 }
118118 * @return {@code true} if the two annotations are {@code equal} or both
119119 * {@code null}
120120 */
121 public static boolean equals(Annotation a1, Annotation a2) {
121 public static boolean equals(final Annotation a1, final Annotation a2) {
122122 if (a1 == a2) {
123123 return true;
124124 }
125125 if (a1 == null || a2 == null) {
126126 return false;
127127 }
128 Class<? extends Annotation> type = a1.annotationType();
129 Class<? extends Annotation> type2 = a2.annotationType();
128 final Class<? extends Annotation> type = a1.annotationType();
129 final Class<? extends Annotation> type2 = a2.annotationType();
130130 Validate.notNull(type, "Annotation %s with null annotationType()", a1);
131131 Validate.notNull(type2, "Annotation %s with null annotationType()", a2);
132132 if (!type.equals(type2)) {
133133 return false;
134134 }
135135 try {
136 for (Method m : type.getDeclaredMethods()) {
136 for (final Method m : type.getDeclaredMethods()) {
137137 if (m.getParameterTypes().length == 0
138138 && isValidAnnotationMemberType(m.getReturnType())) {
139 Object v1 = m.invoke(a1);
140 Object v2 = m.invoke(a2);
139 final Object v1 = m.invoke(a1);
140 final Object v2 = m.invoke(a2);
141141 if (!memberEquals(m.getReturnType(), v1, v2)) {
142142 return false;
143143 }
144144 }
145145 }
146 } catch (IllegalAccessException ex) {
147 return false;
148 } catch (InvocationTargetException ex) {
146 } catch (final IllegalAccessException ex) {
147 return false;
148 } catch (final InvocationTargetException ex) {
149149 return false;
150150 }
151151 return true;
163163 * @throws IllegalStateException if an annotation method invocation returns
164164 * {@code null}
165165 */
166 public static int hashCode(Annotation a) {
166 public static int hashCode(final Annotation a) {
167167 int result = 0;
168 Class<? extends Annotation> type = a.annotationType();
169 for (Method m : type.getDeclaredMethods()) {
168 final Class<? extends Annotation> type = a.annotationType();
169 for (final Method m : type.getDeclaredMethods()) {
170170 try {
171 Object value = m.invoke(a);
171 final Object value = m.invoke(a);
172172 if (value == null) {
173173 throw new IllegalStateException(
174174 String.format("Annotation method %s returned null", m));
175175 }
176176 result += hashMember(m.getName(), value);
177 } catch (RuntimeException ex) {
177 } catch (final RuntimeException ex) {
178178 throw ex;
179 } catch (Exception ex) {
179 } catch (final Exception ex) {
180180 throw new RuntimeException(ex);
181181 }
182182 }
192192 * {@code null}
193193 */
194194 public static String toString(final Annotation a) {
195 ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
196 for (Method m : a.annotationType().getDeclaredMethods()) {
195 final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
196 for (final Method m : a.annotationType().getDeclaredMethods()) {
197197 if (m.getParameterTypes().length > 0) {
198198 continue; //wtf?
199199 }
200200 try {
201201 builder.append(m.getName(), m.invoke(a));
202 } catch (RuntimeException ex) {
202 } catch (final RuntimeException ex) {
203203 throw ex;
204 } catch (Exception ex) {
204 } catch (final Exception ex) {
205205 throw new RuntimeException(ex);
206206 }
207207 }
238238 * @param value the value of the member
239239 * @return a hash code for this member
240240 */
241 private static int hashMember(String name, Object value) {
242 int part1 = name.hashCode() * 127;
241 private static int hashMember(final String name, final Object value) {
242 final int part1 = name.hashCode() * 127;
243243 if (value.getClass().isArray()) {
244244 return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value);
245245 }
259259 * @param o2 the second object
260260 * @return a flag whether these objects are equal
261261 */
262 private static boolean memberEquals(Class<?> type, Object o1, Object o2) {
262 private static boolean memberEquals(final Class<?> type, final Object o1, final Object o2) {
263263 if (o1 == o2) {
264264 return true;
265265 }
283283 * @param o2 the second object
284284 * @return a flag whether these objects are equal
285285 */
286 private static boolean arrayMemberEquals(Class<?> componentType, Object o1, Object o2) {
286 private static boolean arrayMemberEquals(final Class<?> componentType, final Object o1, final Object o2) {
287287 if (componentType.isAnnotation()) {
288288 return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2);
289289 }
321321 * @param a2 the second array
322322 * @return a flag whether these arrays are equal
323323 */
324 private static boolean annotationArrayMemberEquals(Annotation[] a1, Annotation[] a2) {
324 private static boolean annotationArrayMemberEquals(final Annotation[] a1, final Annotation[] a2) {
325325 if (a1.length != a2.length) {
326326 return false;
327327 }
340340 * @param o the array
341341 * @return a hash code for the specified array
342342 */
343 private static int arrayMemberHash(Class<?> componentType, Object o) {
343 private static int arrayMemberHash(final Class<?> componentType, final Object o) {
344344 if (componentType.equals(Byte.TYPE)) {
345345 return Arrays.hashCode((byte[]) o);
346346 }
1717
1818 import java.lang.reflect.Array;
1919 import java.util.Arrays;
20 import java.util.BitSet;
2021 import java.util.HashMap;
21 import java.util.HashSet;
2222 import java.util.Map;
2323
2424 import org.apache.commons.lang3.builder.EqualsBuilder;
3838 *
3939 * <p>#ThreadSafe#</p>
4040 * @since 2.0
41 * @version $Id: ArrayUtils.java 1154216 2011-08-05 13:57:16Z mbenson $
41 * @version $Id: ArrayUtils.java 1553927 2013-12-28 21:17:57Z ggregory $
4242 */
4343 public class ArrayUtils {
4444
154154 * @param array the array to get a toString for, may be {@code null}
155155 * @return a String representation of the array, '{}' if null array input
156156 */
157 public static String toString(Object array) {
157 public static String toString(final Object array) {
158158 return toString(array, "{}");
159159 }
160160
170170 * @param stringIfNull the String to return if the array is {@code null}
171171 * @return a String representation of the array
172172 */
173 public static String toString(Object array, String stringIfNull) {
173 public static String toString(final Object array, final String stringIfNull) {
174174 if (array == null) {
175175 return stringIfNull;
176176 }
185185 * @param array the array to get a hash code for, {@code null} returns zero
186186 * @return a hash code for the array
187187 */
188 public static int hashCode(Object array) {
188 public static int hashCode(final Object array) {
189189 return new HashCodeBuilder().append(array).toHashCode();
190190 }
191191
198198 * @param array1 the left hand array to compare, may be {@code null}
199199 * @param array2 the right hand array to compare, may be {@code null}
200200 * @return {@code true} if the arrays are equal
201 */
202 public static boolean isEquals(Object array1, Object array2) {
201 * @deprecated this method has been replaced by {@code java.util.Objects.deepEquals(Object, Object)} and will be
202 * removed from future releases.
203 */
204 @Deprecated
205 public static boolean isEquals(final Object array1, final Object array2) {
203206 return new EqualsBuilder().append(array1, array2).isEquals();
204207 }
205208
230233 * @throws IllegalArgumentException if the array contains elements other
231234 * than {@link java.util.Map.Entry} and an Array
232235 */
233 public static Map<Object, Object> toMap(Object[] array) {
236 public static Map<Object, Object> toMap(final Object[] array) {
234237 if (array == null) {
235238 return null;
236239 }
237240 final Map<Object, Object> map = new HashMap<Object, Object>((int) (array.length * 1.5));
238241 for (int i = 0; i < array.length; i++) {
239 Object object = array[i];
242 final Object object = array[i];
240243 if (object instanceof Map.Entry<?, ?>) {
241 Map.Entry<?,?> entry = (Map.Entry<?,?>) object;
244 final Map.Entry<?,?> entry = (Map.Entry<?,?>) object;
242245 map.put(entry.getKey(), entry.getValue());
243246 } else if (object instanceof Object[]) {
244 Object[] entry = (Object[]) object;
247 final Object[] entry = (Object[]) object;
245248 if (entry.length < 2) {
246249 throw new IllegalArgumentException("Array element " + i + ", '"
247250 + object
315318 * @param array the array to shallow clone, may be {@code null}
316319 * @return the cloned array, {@code null} if {@code null} input
317320 */
318 public static <T> T[] clone(T[] array) {
321 public static <T> T[] clone(final T[] array) {
319322 if (array == null) {
320323 return null;
321324 }
331334 * @param array the array to clone, may be {@code null}
332335 * @return the cloned array, {@code null} if {@code null} input
333336 */
334 public static long[] clone(long[] array) {
337 public static long[] clone(final long[] array) {
335338 if (array == null) {
336339 return null;
337340 }
347350 * @param array the array to clone, may be {@code null}
348351 * @return the cloned array, {@code null} if {@code null} input
349352 */
350 public static int[] clone(int[] array) {
353 public static int[] clone(final int[] array) {
351354 if (array == null) {
352355 return null;
353356 }
363366 * @param array the array to clone, may be {@code null}
364367 * @return the cloned array, {@code null} if {@code null} input
365368 */
366 public static short[] clone(short[] array) {
369 public static short[] clone(final short[] array) {
367370 if (array == null) {
368371 return null;
369372 }
379382 * @param array the array to clone, may be {@code null}
380383 * @return the cloned array, {@code null} if {@code null} input
381384 */
382 public static char[] clone(char[] array) {
385 public static char[] clone(final char[] array) {
383386 if (array == null) {
384387 return null;
385388 }
395398 * @param array the array to clone, may be {@code null}
396399 * @return the cloned array, {@code null} if {@code null} input
397400 */
398 public static byte[] clone(byte[] array) {
401 public static byte[] clone(final byte[] array) {
399402 if (array == null) {
400403 return null;
401404 }
411414 * @param array the array to clone, may be {@code null}
412415 * @return the cloned array, {@code null} if {@code null} input
413416 */
414 public static double[] clone(double[] array) {
417 public static double[] clone(final double[] array) {
415418 if (array == null) {
416419 return null;
417420 }
427430 * @param array the array to clone, may be {@code null}
428431 * @return the cloned array, {@code null} if {@code null} input
429432 */
430 public static float[] clone(float[] array) {
433 public static float[] clone(final float[] array) {
431434 if (array == null) {
432435 return null;
433436 }
443446 * @param array the array to clone, may be {@code null}
444447 * @return the cloned array, {@code null} if {@code null} input
445448 */
446 public static boolean[] clone(boolean[] array) {
449 public static boolean[] clone(final boolean[] array) {
447450 if (array == null) {
448451 return null;
449452 }
465468 * @return the same array, {@code public static} empty array if {@code null} or empty input
466469 * @since 2.5
467470 */
468 public static Object[] nullToEmpty(Object[] array) {
471 public static Object[] nullToEmpty(final Object[] array) {
469472 if (array == null || array.length == 0) {
470473 return EMPTY_OBJECT_ARRAY;
474 }
475 return array;
476 }
477
478 /**
479 * <p>Defensive programming technique to change a {@code null}
480 * reference to an empty one.</p>
481 *
482 * <p>This method returns an empty array for a {@code null} input array.</p>
483 *
484 * <p>As a memory optimizing technique an empty array passed in will be overridden with
485 * the empty {@code public static} references in this class.</p>
486 *
487 * @param array the array to check for {@code null} or empty
488 * @return the same array, {@code public static} empty array if {@code null} or empty input
489 * @since 3.2
490 */
491 public static Class<?>[] nullToEmpty(final Class<?>[] array) {
492 if (array == null || array.length == 0) {
493 return EMPTY_CLASS_ARRAY;
471494 }
472495 return array;
473496 }
485508 * @return the same array, {@code public static} empty array if {@code null} or empty input
486509 * @since 2.5
487510 */
488 public static String[] nullToEmpty(String[] array) {
511 public static String[] nullToEmpty(final String[] array) {
489512 if (array == null || array.length == 0) {
490513 return EMPTY_STRING_ARRAY;
491514 }
505528 * @return the same array, {@code public static} empty array if {@code null} or empty input
506529 * @since 2.5
507530 */
508 public static long[] nullToEmpty(long[] array) {
531 public static long[] nullToEmpty(final long[] array) {
509532 if (array == null || array.length == 0) {
510533 return EMPTY_LONG_ARRAY;
511534 }
525548 * @return the same array, {@code public static} empty array if {@code null} or empty input
526549 * @since 2.5
527550 */
528 public static int[] nullToEmpty(int[] array) {
551 public static int[] nullToEmpty(final int[] array) {
529552 if (array == null || array.length == 0) {
530553 return EMPTY_INT_ARRAY;
531554 }
545568 * @return the same array, {@code public static} empty array if {@code null} or empty input
546569 * @since 2.5
547570 */
548 public static short[] nullToEmpty(short[] array) {
571 public static short[] nullToEmpty(final short[] array) {
549572 if (array == null || array.length == 0) {
550573 return EMPTY_SHORT_ARRAY;
551574 }
565588 * @return the same array, {@code public static} empty array if {@code null} or empty input
566589 * @since 2.5
567590 */
568 public static char[] nullToEmpty(char[] array) {
591 public static char[] nullToEmpty(final char[] array) {
569592 if (array == null || array.length == 0) {
570593 return EMPTY_CHAR_ARRAY;
571594 }
585608 * @return the same array, {@code public static} empty array if {@code null} or empty input
586609 * @since 2.5
587610 */
588 public static byte[] nullToEmpty(byte[] array) {
611 public static byte[] nullToEmpty(final byte[] array) {
589612 if (array == null || array.length == 0) {
590613 return EMPTY_BYTE_ARRAY;
591614 }
605628 * @return the same array, {@code public static} empty array if {@code null} or empty input
606629 * @since 2.5
607630 */
608 public static double[] nullToEmpty(double[] array) {
631 public static double[] nullToEmpty(final double[] array) {
609632 if (array == null || array.length == 0) {
610633 return EMPTY_DOUBLE_ARRAY;
611634 }
625648 * @return the same array, {@code public static} empty array if {@code null} or empty input
626649 * @since 2.5
627650 */
628 public static float[] nullToEmpty(float[] array) {
651 public static float[] nullToEmpty(final float[] array) {
629652 if (array == null || array.length == 0) {
630653 return EMPTY_FLOAT_ARRAY;
631654 }
645668 * @return the same array, {@code public static} empty array if {@code null} or empty input
646669 * @since 2.5
647670 */
648 public static boolean[] nullToEmpty(boolean[] array) {
671 public static boolean[] nullToEmpty(final boolean[] array) {
649672 if (array == null || array.length == 0) {
650673 return EMPTY_BOOLEAN_ARRAY;
651674 }
665688 * @return the same array, {@code public static} empty array if {@code null} or empty input
666689 * @since 2.5
667690 */
668 public static Long[] nullToEmpty(Long[] array) {
691 public static Long[] nullToEmpty(final Long[] array) {
669692 if (array == null || array.length == 0) {
670693 return EMPTY_LONG_OBJECT_ARRAY;
671694 }
685708 * @return the same array, {@code public static} empty array if {@code null} or empty input
686709 * @since 2.5
687710 */
688 public static Integer[] nullToEmpty(Integer[] array) {
711 public static Integer[] nullToEmpty(final Integer[] array) {
689712 if (array == null || array.length == 0) {
690713 return EMPTY_INTEGER_OBJECT_ARRAY;
691714 }
705728 * @return the same array, {@code public static} empty array if {@code null} or empty input
706729 * @since 2.5
707730 */
708 public static Short[] nullToEmpty(Short[] array) {
731 public static Short[] nullToEmpty(final Short[] array) {
709732 if (array == null || array.length == 0) {
710733 return EMPTY_SHORT_OBJECT_ARRAY;
711734 }
725748 * @return the same array, {@code public static} empty array if {@code null} or empty input
726749 * @since 2.5
727750 */
728 public static Character[] nullToEmpty(Character[] array) {
751 public static Character[] nullToEmpty(final Character[] array) {
729752 if (array == null || array.length == 0) {
730753 return EMPTY_CHARACTER_OBJECT_ARRAY;
731754 }
745768 * @return the same array, {@code public static} empty array if {@code null} or empty input
746769 * @since 2.5
747770 */
748 public static Byte[] nullToEmpty(Byte[] array) {
771 public static Byte[] nullToEmpty(final Byte[] array) {
749772 if (array == null || array.length == 0) {
750773 return EMPTY_BYTE_OBJECT_ARRAY;
751774 }
765788 * @return the same array, {@code public static} empty array if {@code null} or empty input
766789 * @since 2.5
767790 */
768 public static Double[] nullToEmpty(Double[] array) {
791 public static Double[] nullToEmpty(final Double[] array) {
769792 if (array == null || array.length == 0) {
770793 return EMPTY_DOUBLE_OBJECT_ARRAY;
771794 }
785808 * @return the same array, {@code public static} empty array if {@code null} or empty input
786809 * @since 2.5
787810 */
788 public static Float[] nullToEmpty(Float[] array) {
811 public static Float[] nullToEmpty(final Float[] array) {
789812 if (array == null || array.length == 0) {
790813 return EMPTY_FLOAT_OBJECT_ARRAY;
791814 }
805828 * @return the same array, {@code public static} empty array if {@code null} or empty input
806829 * @since 2.5
807830 */
808 public static Boolean[] nullToEmpty(Boolean[] array) {
831 public static Boolean[] nullToEmpty(final Boolean[] array) {
809832 if (array == null || array.length == 0) {
810833 return EMPTY_BOOLEAN_OBJECT_ARRAY;
811834 }
841864 * @return a new array containing the elements between
842865 * the start and end indices.
843866 * @since 2.1
844 */
845 public static <T> T[] subarray(T[] array, int startIndexInclusive, int endIndexExclusive) {
867 * @see Arrays#copyOfRange(Object[], int, int)
868 */
869 public static <T> T[] subarray(final T[] array, int startIndexInclusive, int endIndexExclusive) {
846870 if (array == null) {
847871 return null;
848872 }
852876 if (endIndexExclusive > array.length) {
853877 endIndexExclusive = array.length;
854878 }
855 int newSize = endIndexExclusive - startIndexInclusive;
856 Class<?> type = array.getClass().getComponentType();
879 final int newSize = endIndexExclusive - startIndexInclusive;
880 final Class<?> type = array.getClass().getComponentType();
857881 if (newSize <= 0) {
858882 @SuppressWarnings("unchecked") // OK, because array is of type T
859883 final T[] emptyArray = (T[]) Array.newInstance(type, 0);
860884 return emptyArray;
861885 }
862886 @SuppressWarnings("unchecked") // OK, because array is of type T
887 final
863888 T[] subarray = (T[]) Array.newInstance(type, newSize);
864889 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
865890 return subarray;
883908 * @return a new array containing the elements between
884909 * the start and end indices.
885910 * @since 2.1
886 */
887 public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) {
911 * @see Arrays#copyOfRange(long[], int, int)
912 */
913 public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {
888914 if (array == null) {
889915 return null;
890916 }
894920 if (endIndexExclusive > array.length) {
895921 endIndexExclusive = array.length;
896922 }
897 int newSize = endIndexExclusive - startIndexInclusive;
923 final int newSize = endIndexExclusive - startIndexInclusive;
898924 if (newSize <= 0) {
899925 return EMPTY_LONG_ARRAY;
900926 }
901927
902 long[] subarray = new long[newSize];
928 final long[] subarray = new long[newSize];
903929 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
904930 return subarray;
905931 }
922948 * @return a new array containing the elements between
923949 * the start and end indices.
924950 * @since 2.1
925 */
926 public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) {
951 * @see Arrays#copyOfRange(int[], int, int)
952 */
953 public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {
927954 if (array == null) {
928955 return null;
929956 }
933960 if (endIndexExclusive > array.length) {
934961 endIndexExclusive = array.length;
935962 }
936 int newSize = endIndexExclusive - startIndexInclusive;
963 final int newSize = endIndexExclusive - startIndexInclusive;
937964 if (newSize <= 0) {
938965 return EMPTY_INT_ARRAY;
939966 }
940967
941 int[] subarray = new int[newSize];
968 final int[] subarray = new int[newSize];
942969 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
943970 return subarray;
944971 }
961988 * @return a new array containing the elements between
962989 * the start and end indices.
963990 * @since 2.1
964 */
965 public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) {
991 * @see Arrays#copyOfRange(short[], int, int)
992 */
993 public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {
966994 if (array == null) {
967995 return null;
968996 }
9721000 if (endIndexExclusive > array.length) {
9731001 endIndexExclusive = array.length;
9741002 }
975 int newSize = endIndexExclusive - startIndexInclusive;
1003 final int newSize = endIndexExclusive - startIndexInclusive;
9761004 if (newSize <= 0) {
9771005 return EMPTY_SHORT_ARRAY;
9781006 }
9791007
980 short[] subarray = new short[newSize];
1008 final short[] subarray = new short[newSize];
9811009 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
9821010 return subarray;
9831011 }
10001028 * @return a new array containing the elements between
10011029 * the start and end indices.
10021030 * @since 2.1
1003 */
1004 public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) {
1031 * @see Arrays#copyOfRange(char[], int, int)
1032 */
1033 public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {
10051034 if (array == null) {
10061035 return null;
10071036 }
10111040 if (endIndexExclusive > array.length) {
10121041 endIndexExclusive = array.length;
10131042 }
1014 int newSize = endIndexExclusive - startIndexInclusive;
1043 final int newSize = endIndexExclusive - startIndexInclusive;
10151044 if (newSize <= 0) {
10161045 return EMPTY_CHAR_ARRAY;
10171046 }
10181047
1019 char[] subarray = new char[newSize];
1048 final char[] subarray = new char[newSize];
10201049 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
10211050 return subarray;
10221051 }
10391068 * @return a new array containing the elements between
10401069 * the start and end indices.
10411070 * @since 2.1
1042 */
1043 public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
1071 * @see Arrays#copyOfRange(byte[], int, int)
1072 */
1073 public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {
10441074 if (array == null) {
10451075 return null;
10461076 }
10501080 if (endIndexExclusive > array.length) {
10511081 endIndexExclusive = array.length;
10521082 }
1053 int newSize = endIndexExclusive - startIndexInclusive;
1083 final int newSize = endIndexExclusive - startIndexInclusive;
10541084 if (newSize <= 0) {
10551085 return EMPTY_BYTE_ARRAY;
10561086 }
10571087
1058 byte[] subarray = new byte[newSize];
1088 final byte[] subarray = new byte[newSize];
10591089 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
10601090 return subarray;
10611091 }
10781108 * @return a new array containing the elements between
10791109 * the start and end indices.
10801110 * @since 2.1
1081 */
1082 public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) {
1111 * @see Arrays#copyOfRange(double[], int, int)
1112 */
1113 public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {
10831114 if (array == null) {
10841115 return null;
10851116 }
10891120 if (endIndexExclusive > array.length) {
10901121 endIndexExclusive = array.length;
10911122 }
1092 int newSize = endIndexExclusive - startIndexInclusive;
1123 final int newSize = endIndexExclusive - startIndexInclusive;
10931124 if (newSize <= 0) {
10941125 return EMPTY_DOUBLE_ARRAY;
10951126 }
10961127
1097 double[] subarray = new double[newSize];
1128 final double[] subarray = new double[newSize];
10981129 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
10991130 return subarray;
11001131 }
11171148 * @return a new array containing the elements between
11181149 * the start and end indices.
11191150 * @since 2.1
1120 */
1121 public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) {
1151 * @see Arrays#copyOfRange(float[], int, int)
1152 */
1153 public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {
11221154 if (array == null) {
11231155 return null;
11241156 }
11281160 if (endIndexExclusive > array.length) {
11291161 endIndexExclusive = array.length;
11301162 }
1131 int newSize = endIndexExclusive - startIndexInclusive;
1163 final int newSize = endIndexExclusive - startIndexInclusive;
11321164 if (newSize <= 0) {
11331165 return EMPTY_FLOAT_ARRAY;
11341166 }
11351167
1136 float[] subarray = new float[newSize];
1168 final float[] subarray = new float[newSize];
11371169 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
11381170 return subarray;
11391171 }
11561188 * @return a new array containing the elements between
11571189 * the start and end indices.
11581190 * @since 2.1
1159 */
1160 public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) {
1191 * @see Arrays#copyOfRange(boolean[], int, int)
1192 */
1193 public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {
11611194 if (array == null) {
11621195 return null;
11631196 }
11671200 if (endIndexExclusive > array.length) {
11681201 endIndexExclusive = array.length;
11691202 }
1170 int newSize = endIndexExclusive - startIndexInclusive;
1203 final int newSize = endIndexExclusive - startIndexInclusive;
11711204 if (newSize <= 0) {
11721205 return EMPTY_BOOLEAN_ARRAY;
11731206 }
11741207
1175 boolean[] subarray = new boolean[newSize];
1208 final boolean[] subarray = new boolean[newSize];
11761209 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
11771210 return subarray;
11781211 }
11901223 * @return {@code true} if length of arrays matches, treating
11911224 * {@code null} as an empty array
11921225 */
1193 public static boolean isSameLength(Object[] array1, Object[] array2) {
1226 public static boolean isSameLength(final Object[] array1, final Object[] array2) {
11941227 if ((array1 == null && array2 != null && array2.length > 0) ||
11951228 (array2 == null && array1 != null && array1.length > 0) ||
11961229 (array1 != null && array2 != null && array1.length != array2.length)) {
12081241 * @return {@code true} if length of arrays matches, treating
12091242 * {@code null} as an empty array
12101243 */
1211 public static boolean isSameLength(long[] array1, long[] array2) {
1244 public static boolean isSameLength(final long[] array1, final long[] array2) {
12121245 if ((array1 == null && array2 != null && array2.length > 0) ||
12131246 (array2 == null && array1 != null && array1.length > 0) ||
12141247 (array1 != null && array2 != null && array1.length != array2.length)) {
12261259 * @return {@code true} if length of arrays matches, treating
12271260 * {@code null} as an empty array
12281261 */
1229 public static boolean isSameLength(int[] array1, int[] array2) {
1262 public static boolean isSameLength(final int[] array1, final int[] array2) {
12301263 if ((array1 == null && array2 != null && array2.length > 0) ||
12311264 (array2 == null && array1 != null && array1.length > 0) ||
12321265 (array1 != null && array2 != null && array1.length != array2.length)) {
12441277 * @return {@code true} if length of arrays matches, treating
12451278 * {@code null} as an empty array
12461279 */
1247 public static boolean isSameLength(short[] array1, short[] array2) {
1280 public static boolean isSameLength(final short[] array1, final short[] array2) {
12481281 if ((array1 == null && array2 != null && array2.length > 0) ||
12491282 (array2 == null && array1 != null && array1.length > 0) ||
12501283 (array1 != null && array2 != null && array1.length != array2.length)) {
12621295 * @return {@code true} if length of arrays matches, treating
12631296 * {@code null} as an empty array
12641297 */
1265 public static boolean isSameLength(char[] array1, char[] array2) {
1298 public static boolean isSameLength(final char[] array1, final char[] array2) {
12661299 if ((array1 == null && array2 != null && array2.length > 0) ||
12671300 (array2 == null && array1 != null && array1.length > 0) ||
12681301 (array1 != null && array2 != null && array1.length != array2.length)) {
12801313 * @return {@code true} if length of arrays matches, treating
12811314 * {@code null} as an empty array
12821315 */
1283 public static boolean isSameLength(byte[] array1, byte[] array2) {
1316 public static boolean isSameLength(final byte[] array1, final byte[] array2) {
12841317 if ((array1 == null && array2 != null && array2.length > 0) ||
12851318 (array2 == null && array1 != null && array1.length > 0) ||
12861319 (array1 != null && array2 != null && array1.length != array2.length)) {
12981331 * @return {@code true} if length of arrays matches, treating
12991332 * {@code null} as an empty array
13001333 */
1301 public static boolean isSameLength(double[] array1, double[] array2) {
1334 public static boolean isSameLength(final double[] array1, final double[] array2) {
13021335 if ((array1 == null && array2 != null && array2.length > 0) ||
13031336 (array2 == null && array1 != null && array1.length > 0) ||
13041337 (array1 != null && array2 != null && array1.length != array2.length)) {
13161349 * @return {@code true} if length of arrays matches, treating
13171350 * {@code null} as an empty array
13181351 */
1319 public static boolean isSameLength(float[] array1, float[] array2) {
1352 public static boolean isSameLength(final float[] array1, final float[] array2) {
13201353 if ((array1 == null && array2 != null && array2.length > 0) ||
13211354 (array2 == null && array1 != null && array1.length > 0) ||
13221355 (array1 != null && array2 != null && array1.length != array2.length)) {
13341367 * @return {@code true} if length of arrays matches, treating
13351368 * {@code null} as an empty array
13361369 */
1337 public static boolean isSameLength(boolean[] array1, boolean[] array2) {
1370 public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {
13381371 if ((array1 == null && array2 != null && array2.length > 0) ||
13391372 (array2 == null && array1 != null && array1.length > 0) ||
13401373 (array1 != null && array2 != null && array1.length != array2.length)) {
13611394 *
13621395 * @param array the array to retrieve the length from, may be null
13631396 * @return The length of the array, or {@code 0} if the array is {@code null}
1364 * @throws IllegalArgumentException if the object arguement is not an array.
1397 * @throws IllegalArgumentException if the object argument is not an array.
13651398 * @since 2.1
13661399 */
1367 public static int getLength(Object array) {
1400 public static int getLength(final Object array) {
13681401 if (array == null) {
13691402 return 0;
13701403 }
13801413 * @return {@code true} if type of arrays matches
13811414 * @throws IllegalArgumentException if either array is {@code null}
13821415 */
1383 public static boolean isSameType(Object array1, Object array2) {
1416 public static boolean isSameType(final Object array1, final Object array2) {
13841417 if (array1 == null || array2 == null) {
13851418 throw new IllegalArgumentException("The Array must not be null");
13861419 }
13981431 *
13991432 * @param array the array to reverse, may be {@code null}
14001433 */
1401 public static void reverse(Object[] array) {
1434 public static void reverse(final Object[] array) {
14021435 if (array == null) {
14031436 return;
14041437 }
1405 int i = 0;
1406 int j = array.length - 1;
1438 reverse(array, 0, array.length);
1439 }
1440
1441 /**
1442 * <p>Reverses the order of the given array.</p>
1443 *
1444 * <p>This method does nothing for a {@code null} input array.</p>
1445 *
1446 * @param array the array to reverse, may be {@code null}
1447 */
1448 public static void reverse(final long[] array) {
1449 if (array == null) {
1450 return;
1451 }
1452 reverse(array, 0, array.length);
1453 }
1454
1455 /**
1456 * <p>Reverses the order of the given array.</p>
1457 *
1458 * <p>This method does nothing for a {@code null} input array.</p>
1459 *
1460 * @param array the array to reverse, may be {@code null}
1461 */
1462 public static void reverse(final int[] array) {
1463 if (array == null) {
1464 return;
1465 }
1466 reverse(array, 0, array.length);
1467 }
1468
1469 /**
1470 * <p>Reverses the order of the given array.</p>
1471 *
1472 * <p>This method does nothing for a {@code null} input array.</p>
1473 *
1474 * @param array the array to reverse, may be {@code null}
1475 */
1476 public static void reverse(final short[] array) {
1477 if (array == null) {
1478 return;
1479 }
1480 reverse(array, 0, array.length);
1481 }
1482
1483 /**
1484 * <p>Reverses the order of the given array.</p>
1485 *
1486 * <p>This method does nothing for a {@code null} input array.</p>
1487 *
1488 * @param array the array to reverse, may be {@code null}
1489 */
1490 public static void reverse(final char[] array) {
1491 if (array == null) {
1492 return;
1493 }
1494 reverse(array, 0, array.length);
1495 }
1496
1497 /**
1498 * <p>Reverses the order of the given array.</p>
1499 *
1500 * <p>This method does nothing for a {@code null} input array.</p>
1501 *
1502 * @param array the array to reverse, may be {@code null}
1503 */
1504 public static void reverse(final byte[] array) {
1505 if (array == null) {
1506 return;
1507 }
1508 reverse(array, 0, array.length);
1509 }
1510
1511 /**
1512 * <p>Reverses the order of the given array.</p>
1513 *
1514 * <p>This method does nothing for a {@code null} input array.</p>
1515 *
1516 * @param array the array to reverse, may be {@code null}
1517 */
1518 public static void reverse(final double[] array) {
1519 if (array == null) {
1520 return;
1521 }
1522 reverse(array, 0, array.length);
1523 }
1524
1525 /**
1526 * <p>Reverses the order of the given array.</p>
1527 *
1528 * <p>This method does nothing for a {@code null} input array.</p>
1529 *
1530 * @param array the array to reverse, may be {@code null}
1531 */
1532 public static void reverse(final float[] array) {
1533 if (array == null) {
1534 return;
1535 }
1536 reverse(array, 0, array.length);
1537 }
1538
1539 /**
1540 * <p>Reverses the order of the given array.</p>
1541 *
1542 * <p>This method does nothing for a {@code null} input array.</p>
1543 *
1544 * @param array the array to reverse, may be {@code null}
1545 */
1546 public static void reverse(final boolean[] array) {
1547 if (array == null) {
1548 return;
1549 }
1550 reverse(array, 0, array.length);
1551 }
1552
1553 /**
1554 * <p>
1555 * Reverses the order of the given array in the given range.
1556 * </p>
1557 *
1558 * <p>
1559 * This method does nothing for a {@code null} input array.
1560 * </p>
1561 *
1562 * @param array
1563 * the array to reverse, may be {@code null}
1564 * @param startIndexInclusive
1565 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1566 * change.
1567 * @param endIndexExclusive
1568 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1569 * change. Overvalue (&gt;array.length) is demoted to array length.
1570 * @since 3.2
1571 */
1572 public static void reverse(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {
1573 if (array == null) {
1574 return;
1575 }
1576 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1577 int j = Math.min(array.length, endIndexExclusive) - 1;
1578 boolean tmp;
1579 while (j > i) {
1580 tmp = array[j];
1581 array[j] = array[i];
1582 array[i] = tmp;
1583 j--;
1584 i++;
1585 }
1586 }
1587
1588 /**
1589 * <p>
1590 * Reverses the order of the given array in the given range.
1591 * </p>
1592 *
1593 * <p>
1594 * This method does nothing for a {@code null} input array.
1595 * </p>
1596 *
1597 * @param array
1598 * the array to reverse, may be {@code null}
1599 * @param startIndexInclusive
1600 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1601 * change.
1602 * @param endIndexExclusive
1603 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1604 * change. Overvalue (&gt;array.length) is demoted to array length.
1605 * @since 3.2
1606 */
1607 public static void reverse(final byte[] array, int startIndexInclusive, int endIndexExclusive) {
1608 if (array == null) {
1609 return;
1610 }
1611 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1612 int j = Math.min(array.length, endIndexExclusive) - 1;
1613 byte tmp;
1614 while (j > i) {
1615 tmp = array[j];
1616 array[j] = array[i];
1617 array[i] = tmp;
1618 j--;
1619 i++;
1620 }
1621 }
1622
1623 /**
1624 * <p>
1625 * Reverses the order of the given array in the given range.
1626 * </p>
1627 *
1628 * <p>
1629 * This method does nothing for a {@code null} input array.
1630 * </p>
1631 *
1632 * @param array
1633 * the array to reverse, may be {@code null}
1634 * @param startIndexInclusive
1635 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1636 * change.
1637 * @param endIndexExclusive
1638 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1639 * change. Overvalue (&gt;array.length) is demoted to array length.
1640 * @since 3.2
1641 */
1642 public static void reverse(final char[] array, int startIndexInclusive, int endIndexExclusive) {
1643 if (array == null) {
1644 return;
1645 }
1646 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1647 int j = Math.min(array.length, endIndexExclusive) - 1;
1648 char tmp;
1649 while (j > i) {
1650 tmp = array[j];
1651 array[j] = array[i];
1652 array[i] = tmp;
1653 j--;
1654 i++;
1655 }
1656 }
1657
1658 /**
1659 * <p>
1660 * Reverses the order of the given array in the given range.
1661 * </p>
1662 *
1663 * <p>
1664 * This method does nothing for a {@code null} input array.
1665 * </p>
1666 *
1667 * @param array
1668 * the array to reverse, may be {@code null}
1669 * @param startIndexInclusive
1670 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1671 * change.
1672 * @param endIndexExclusive
1673 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1674 * change. Overvalue (&gt;array.length) is demoted to array length.
1675 * @since 3.2
1676 */
1677 public static void reverse(final double[] array, int startIndexInclusive, int endIndexExclusive) {
1678 if (array == null) {
1679 return;
1680 }
1681 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1682 int j = Math.min(array.length, endIndexExclusive) - 1;
1683 double tmp;
1684 while (j > i) {
1685 tmp = array[j];
1686 array[j] = array[i];
1687 array[i] = tmp;
1688 j--;
1689 i++;
1690 }
1691 }
1692
1693 /**
1694 * <p>
1695 * Reverses the order of the given array in the given range.
1696 * </p>
1697 *
1698 * <p>
1699 * This method does nothing for a {@code null} input array.
1700 * </p>
1701 *
1702 * @param array
1703 * the array to reverse, may be {@code null}
1704 * @param startIndexInclusive
1705 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1706 * change.
1707 * @param endIndexExclusive
1708 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1709 * change. Overvalue (&gt;array.length) is demoted to array length.
1710 * @since 3.2
1711 */
1712 public static void reverse(final float[] array, int startIndexInclusive, int endIndexExclusive) {
1713 if (array == null) {
1714 return;
1715 }
1716 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1717 int j = Math.min(array.length, endIndexExclusive) - 1;
1718 float tmp;
1719 while (j > i) {
1720 tmp = array[j];
1721 array[j] = array[i];
1722 array[i] = tmp;
1723 j--;
1724 i++;
1725 }
1726 }
1727
1728 /**
1729 * <p>
1730 * Reverses the order of the given array in the given range.
1731 * </p>
1732 *
1733 * <p>
1734 * This method does nothing for a {@code null} input array.
1735 * </p>
1736 *
1737 * @param array
1738 * the array to reverse, may be {@code null}
1739 * @param startIndexInclusive
1740 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1741 * change.
1742 * @param endIndexExclusive
1743 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1744 * change. Overvalue (&gt;array.length) is demoted to array length.
1745 * @since 3.2
1746 */
1747 public static void reverse(final int[] array, int startIndexInclusive, int endIndexExclusive) {
1748 if (array == null) {
1749 return;
1750 }
1751 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1752 int j = Math.min(array.length, endIndexExclusive) - 1;
1753 int tmp;
1754 while (j > i) {
1755 tmp = array[j];
1756 array[j] = array[i];
1757 array[i] = tmp;
1758 j--;
1759 i++;
1760 }
1761 }
1762
1763 /**
1764 * <p>
1765 * Reverses the order of the given array in the given range.
1766 * </p>
1767 *
1768 * <p>
1769 * This method does nothing for a {@code null} input array.
1770 * </p>
1771 *
1772 * @param array
1773 * the array to reverse, may be {@code null}
1774 * @param startIndexInclusive
1775 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1776 * change.
1777 * @param endIndexExclusive
1778 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1779 * change. Overvalue (&gt;array.length) is demoted to array length.
1780 * @since 3.2
1781 */
1782 public static void reverse(final long[] array, int startIndexInclusive, int endIndexExclusive) {
1783 if (array == null) {
1784 return;
1785 }
1786 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1787 int j = Math.min(array.length, endIndexExclusive) - 1;
1788 long tmp;
1789 while (j > i) {
1790 tmp = array[j];
1791 array[j] = array[i];
1792 array[i] = tmp;
1793 j--;
1794 i++;
1795 }
1796 }
1797
1798 /**
1799 * <p>
1800 * Reverses the order of the given array in the given range.
1801 * </p>
1802 *
1803 * <p>
1804 * This method does nothing for a {@code null} input array.
1805 * </p>
1806 *
1807 * @param array
1808 * the array to reverse, may be {@code null}
1809 * @param startIndexInclusive
1810 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1811 * change.
1812 * @param endIndexExclusive
1813 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1814 * change. Overvalue (&gt;array.length) is demoted to array length.
1815 * @since 3.2
1816 */
1817 public static void reverse(final Object[] array, int startIndexInclusive, int endIndexExclusive) {
1818 if (array == null) {
1819 return;
1820 }
1821 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1822 int j = Math.min(array.length, endIndexExclusive) - 1;
14071823 Object tmp;
14081824 while (j > i) {
14091825 tmp = array[j];
14151831 }
14161832
14171833 /**
1418 * <p>Reverses the order of the given array.</p>
1419 *
1420 * <p>This method does nothing for a {@code null} input array.</p>
1421 *
1422 * @param array the array to reverse, may be {@code null}
1423 */
1424 public static void reverse(long[] array) {
1834 * <p>
1835 * Reverses the order of the given array in the given range.
1836 * </p>
1837 *
1838 * <p>
1839 * This method does nothing for a {@code null} input array.
1840 * </p>
1841 *
1842 * @param array
1843 * the array to reverse, may be {@code null}
1844 * @param startIndexInclusive
1845 * the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in no
1846 * change.
1847 * @param endIndexExclusive
1848 * elements up to endIndex-1 are reversed in the array. Undervalue (&lt; start index) results in no
1849 * change. Overvalue (&gt;array.length) is demoted to array length.
1850 * @since 3.2
1851 */
1852 public static void reverse(final short[] array, int startIndexInclusive, int endIndexExclusive) {
14251853 if (array == null) {
14261854 return;
14271855 }
1428 int i = 0;
1429 int j = array.length - 1;
1430 long tmp;
1431 while (j > i) {
1432 tmp = array[j];
1433 array[j] = array[i];
1434 array[i] = tmp;
1435 j--;
1436 i++;
1437 }
1438 }
1439
1440 /**
1441 * <p>Reverses the order of the given array.</p>
1442 *
1443 * <p>This method does nothing for a {@code null} input array.</p>
1444 *
1445 * @param array the array to reverse, may be {@code null}
1446 */
1447 public static void reverse(int[] array) {
1448 if (array == null) {
1449 return;
1450 }
1451 int i = 0;
1452 int j = array.length - 1;
1453 int tmp;
1454 while (j > i) {
1455 tmp = array[j];
1456 array[j] = array[i];
1457 array[i] = tmp;
1458 j--;
1459 i++;
1460 }
1461 }
1462
1463 /**
1464 * <p>Reverses the order of the given array.</p>
1465 *
1466 * <p>This method does nothing for a {@code null} input array.</p>
1467 *
1468 * @param array the array to reverse, may be {@code null}
1469 */
1470 public static void reverse(short[] array) {
1471 if (array == null) {
1472 return;
1473 }
1474 int i = 0;
1475 int j = array.length - 1;
1856 int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
1857 int j = Math.min(array.length, endIndexExclusive) - 1;
14761858 short tmp;
14771859 while (j > i) {
14781860 tmp = array[j];
14831865 }
14841866 }
14851867
1486 /**
1487 * <p>Reverses the order of the given array.</p>
1488 *
1489 * <p>This method does nothing for a {@code null} input array.</p>
1490 *
1491 * @param array the array to reverse, may be {@code null}
1492 */
1493 public static void reverse(char[] array) {
1494 if (array == null) {
1495 return;
1496 }
1497 int i = 0;
1498 int j = array.length - 1;
1499 char tmp;
1500 while (j > i) {
1501 tmp = array[j];
1502 array[j] = array[i];
1503 array[i] = tmp;
1504 j--;
1505 i++;
1506 }
1507 }
1508
1509 /**
1510 * <p>Reverses the order of the given array.</p>
1511 *
1512 * <p>This method does nothing for a {@code null} input array.</p>
1513 *
1514 * @param array the array to reverse, may be {@code null}
1515 */
1516 public static void reverse(byte[] array) {
1517 if (array == null) {
1518 return;
1519 }
1520 int i = 0;
1521 int j = array.length - 1;
1522 byte tmp;
1523 while (j > i) {
1524 tmp = array[j];
1525 array[j] = array[i];
1526 array[i] = tmp;
1527 j--;
1528 i++;
1529 }
1530 }
1531
1532 /**
1533 * <p>Reverses the order of the given array.</p>
1534 *
1535 * <p>This method does nothing for a {@code null} input array.</p>
1536 *
1537 * @param array the array to reverse, may be {@code null}
1538 */
1539 public static void reverse(double[] array) {
1540 if (array == null) {
1541 return;
1542 }
1543 int i = 0;
1544 int j = array.length - 1;
1545 double tmp;
1546 while (j > i) {
1547 tmp = array[j];
1548 array[j] = array[i];
1549 array[i] = tmp;
1550 j--;
1551 i++;
1552 }
1553 }
1554
1555 /**
1556 * <p>Reverses the order of the given array.</p>
1557 *
1558 * <p>This method does nothing for a {@code null} input array.</p>
1559 *
1560 * @param array the array to reverse, may be {@code null}
1561 */
1562 public static void reverse(float[] array) {
1563 if (array == null) {
1564 return;
1565 }
1566 int i = 0;
1567 int j = array.length - 1;
1568 float tmp;
1569 while (j > i) {
1570 tmp = array[j];
1571 array[j] = array[i];
1572 array[i] = tmp;
1573 j--;
1574 i++;
1575 }
1576 }
1577
1578 /**
1579 * <p>Reverses the order of the given array.</p>
1580 *
1581 * <p>This method does nothing for a {@code null} input array.</p>
1582 *
1583 * @param array the array to reverse, may be {@code null}
1584 */
1585 public static void reverse(boolean[] array) {
1586 if (array == null) {
1587 return;
1588 }
1589 int i = 0;
1590 int j = array.length - 1;
1591 boolean tmp;
1592 while (j > i) {
1593 tmp = array[j];
1594 array[j] = array[i];
1595 array[i] = tmp;
1596 j--;
1597 i++;
1598 }
1599 }
1600
16011868 // IndexOf search
16021869 // ----------------------------------------------------------------------
16031870
16131880 * @return the index of the object within the array,
16141881 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
16151882 */
1616 public static int indexOf(Object[] array, Object objectToFind) {
1883 public static int indexOf(final Object[] array, final Object objectToFind) {
16171884 return indexOf(array, objectToFind, 0);
16181885 }
16191886
16311898 * @return the index of the object within the array starting at the index,
16321899 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
16331900 */
1634 public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
1901 public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {
16351902 if (array == null) {
16361903 return INDEX_NOT_FOUND;
16371904 }
16641931 * @return the last index of the object within the array,
16651932 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
16661933 */
1667 public static int lastIndexOf(Object[] array, Object objectToFind) {
1934 public static int lastIndexOf(final Object[] array, final Object objectToFind) {
16681935 return lastIndexOf(array, objectToFind, Integer.MAX_VALUE);
16691936 }
16701937
16821949 * @return the last index of the object within the array,
16831950 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
16841951 */
1685 public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) {
1952 public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {
16861953 if (array == null) {
16871954 return INDEX_NOT_FOUND;
16881955 }
17161983 * @param objectToFind the object to find
17171984 * @return {@code true} if the array contains the object
17181985 */
1719 public static boolean contains(Object[] array, Object objectToFind) {
1986 public static boolean contains(final Object[] array, final Object objectToFind) {
17201987 return indexOf(array, objectToFind) != INDEX_NOT_FOUND;
17211988 }
17221989
17321999 * @return the index of the value within the array,
17332000 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
17342001 */
1735 public static int indexOf(long[] array, long valueToFind) {
2002 public static int indexOf(final long[] array, final long valueToFind) {
17362003 return indexOf(array, valueToFind, 0);
17372004 }
17382005
17502017 * @return the index of the value within the array,
17512018 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
17522019 */
1753 public static int indexOf(long[] array, long valueToFind, int startIndex) {
2020 public static int indexOf(final long[] array, final long valueToFind, int startIndex) {
17542021 if (array == null) {
17552022 return INDEX_NOT_FOUND;
17562023 }
17752042 * @return the last index of the value within the array,
17762043 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
17772044 */
1778 public static int lastIndexOf(long[] array, long valueToFind) {
2045 public static int lastIndexOf(final long[] array, final long valueToFind) {
17792046 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
17802047 }
17812048
17932060 * @return the last index of the value within the array,
17942061 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
17952062 */
1796 public static int lastIndexOf(long[] array, long valueToFind, int startIndex) {
2063 public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {
17972064 if (array == null) {
17982065 return INDEX_NOT_FOUND;
17992066 }
18192086 * @param valueToFind the value to find
18202087 * @return {@code true} if the array contains the object
18212088 */
1822 public static boolean contains(long[] array, long valueToFind) {
2089 public static boolean contains(final long[] array, final long valueToFind) {
18232090 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
18242091 }
18252092
18352102 * @return the index of the value within the array,
18362103 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
18372104 */
1838 public static int indexOf(int[] array, int valueToFind) {
2105 public static int indexOf(final int[] array, final int valueToFind) {
18392106 return indexOf(array, valueToFind, 0);
18402107 }
18412108
18532120 * @return the index of the value within the array,
18542121 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
18552122 */
1856 public static int indexOf(int[] array, int valueToFind, int startIndex) {
2123 public static int indexOf(final int[] array, final int valueToFind, int startIndex) {
18572124 if (array == null) {
18582125 return INDEX_NOT_FOUND;
18592126 }
18782145 * @return the last index of the value within the array,
18792146 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
18802147 */
1881 public static int lastIndexOf(int[] array, int valueToFind) {
2148 public static int lastIndexOf(final int[] array, final int valueToFind) {
18822149 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
18832150 }
18842151
18962163 * @return the last index of the value within the array,
18972164 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
18982165 */
1899 public static int lastIndexOf(int[] array, int valueToFind, int startIndex) {
2166 public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {
19002167 if (array == null) {
19012168 return INDEX_NOT_FOUND;
19022169 }
19222189 * @param valueToFind the value to find
19232190 * @return {@code true} if the array contains the object
19242191 */
1925 public static boolean contains(int[] array, int valueToFind) {
2192 public static boolean contains(final int[] array, final int valueToFind) {
19262193 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
19272194 }
19282195
19382205 * @return the index of the value within the array,
19392206 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
19402207 */
1941 public static int indexOf(short[] array, short valueToFind) {
2208 public static int indexOf(final short[] array, final short valueToFind) {
19422209 return indexOf(array, valueToFind, 0);
19432210 }
19442211
19562223 * @return the index of the value within the array,
19572224 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
19582225 */
1959 public static int indexOf(short[] array, short valueToFind, int startIndex) {
2226 public static int indexOf(final short[] array, final short valueToFind, int startIndex) {
19602227 if (array == null) {
19612228 return INDEX_NOT_FOUND;
19622229 }
19812248 * @return the last index of the value within the array,
19822249 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
19832250 */
1984 public static int lastIndexOf(short[] array, short valueToFind) {
2251 public static int lastIndexOf(final short[] array, final short valueToFind) {
19852252 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
19862253 }
19872254
19992266 * @return the last index of the value within the array,
20002267 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
20012268 */
2002 public static int lastIndexOf(short[] array, short valueToFind, int startIndex) {
2269 public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {
20032270 if (array == null) {
20042271 return INDEX_NOT_FOUND;
20052272 }
20252292 * @param valueToFind the value to find
20262293 * @return {@code true} if the array contains the object
20272294 */
2028 public static boolean contains(short[] array, short valueToFind) {
2295 public static boolean contains(final short[] array, final short valueToFind) {
20292296 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
20302297 }
20312298
20422309 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
20432310 * @since 2.1
20442311 */
2045 public static int indexOf(char[] array, char valueToFind) {
2312 public static int indexOf(final char[] array, final char valueToFind) {
20462313 return indexOf(array, valueToFind, 0);
20472314 }
20482315
20612328 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
20622329 * @since 2.1
20632330 */
2064 public static int indexOf(char[] array, char valueToFind, int startIndex) {
2331 public static int indexOf(final char[] array, final char valueToFind, int startIndex) {
20652332 if (array == null) {
20662333 return INDEX_NOT_FOUND;
20672334 }
20872354 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
20882355 * @since 2.1
20892356 */
2090 public static int lastIndexOf(char[] array, char valueToFind) {
2357 public static int lastIndexOf(final char[] array, final char valueToFind) {
20912358 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
20922359 }
20932360
21062373 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
21072374 * @since 2.1
21082375 */
2109 public static int lastIndexOf(char[] array, char valueToFind, int startIndex) {
2376 public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {
21102377 if (array == null) {
21112378 return INDEX_NOT_FOUND;
21122379 }
21332400 * @return {@code true} if the array contains the object
21342401 * @since 2.1
21352402 */
2136 public static boolean contains(char[] array, char valueToFind) {
2403 public static boolean contains(final char[] array, final char valueToFind) {
21372404 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
21382405 }
21392406
21492416 * @return the index of the value within the array,
21502417 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
21512418 */
2152 public static int indexOf(byte[] array, byte valueToFind) {
2419 public static int indexOf(final byte[] array, final byte valueToFind) {
21532420 return indexOf(array, valueToFind, 0);
21542421 }
21552422
21672434 * @return the index of the value within the array,
21682435 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
21692436 */
2170 public static int indexOf(byte[] array, byte valueToFind, int startIndex) {
2437 public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {
21712438 if (array == null) {
21722439 return INDEX_NOT_FOUND;
21732440 }
21922459 * @return the last index of the value within the array,
21932460 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
21942461 */
2195 public static int lastIndexOf(byte[] array, byte valueToFind) {
2462 public static int lastIndexOf(final byte[] array, final byte valueToFind) {
21962463 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
21972464 }
21982465
22102477 * @return the last index of the value within the array,
22112478 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
22122479 */
2213 public static int lastIndexOf(byte[] array, byte valueToFind, int startIndex) {
2480 public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {
22142481 if (array == null) {
22152482 return INDEX_NOT_FOUND;
22162483 }
22362503 * @param valueToFind the value to find
22372504 * @return {@code true} if the array contains the object
22382505 */
2239 public static boolean contains(byte[] array, byte valueToFind) {
2506 public static boolean contains(final byte[] array, final byte valueToFind) {
22402507 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
22412508 }
22422509
22522519 * @return the index of the value within the array,
22532520 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
22542521 */
2255 public static int indexOf(double[] array, double valueToFind) {
2522 public static int indexOf(final double[] array, final double valueToFind) {
22562523 return indexOf(array, valueToFind, 0);
22572524 }
22582525
22692536 * @return the index of the value within the array,
22702537 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
22712538 */
2272 public static int indexOf(double[] array, double valueToFind, double tolerance) {
2539 public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {
22732540 return indexOf(array, valueToFind, 0, tolerance);
22742541 }
22752542
22872554 * @return the index of the value within the array,
22882555 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
22892556 */
2290 public static int indexOf(double[] array, double valueToFind, int startIndex) {
2557 public static int indexOf(final double[] array, final double valueToFind, int startIndex) {
22912558 if (ArrayUtils.isEmpty(array)) {
22922559 return INDEX_NOT_FOUND;
22932560 }
23192586 * @return the index of the value within the array,
23202587 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
23212588 */
2322 public static int indexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
2589 public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {
23232590 if (ArrayUtils.isEmpty(array)) {
23242591 return INDEX_NOT_FOUND;
23252592 }
23262593 if (startIndex < 0) {
23272594 startIndex = 0;
23282595 }
2329 double min = valueToFind - tolerance;
2330 double max = valueToFind + tolerance;
2596 final double min = valueToFind - tolerance;
2597 final double max = valueToFind + tolerance;
23312598 for (int i = startIndex; i < array.length; i++) {
23322599 if (array[i] >= min && array[i] <= max) {
23332600 return i;
23462613 * @return the last index of the value within the array,
23472614 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
23482615 */
2349 public static int lastIndexOf(double[] array, double valueToFind) {
2616 public static int lastIndexOf(final double[] array, final double valueToFind) {
23502617 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
23512618 }
23522619
23632630 * @return the index of the value within the array,
23642631 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
23652632 */
2366 public static int lastIndexOf(double[] array, double valueToFind, double tolerance) {
2633 public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {
23672634 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);
23682635 }
23692636
23812648 * @return the last index of the value within the array,
23822649 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
23832650 */
2384 public static int lastIndexOf(double[] array, double valueToFind, int startIndex) {
2651 public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {
23852652 if (ArrayUtils.isEmpty(array)) {
23862653 return INDEX_NOT_FOUND;
23872654 }
24152682 * @return the last index of the value within the array,
24162683 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
24172684 */
2418 public static int lastIndexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
2685 public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {
24192686 if (ArrayUtils.isEmpty(array)) {
24202687 return INDEX_NOT_FOUND;
24212688 }
24242691 } else if (startIndex >= array.length) {
24252692 startIndex = array.length - 1;
24262693 }
2427 double min = valueToFind - tolerance;
2428 double max = valueToFind + tolerance;
2694 final double min = valueToFind - tolerance;
2695 final double max = valueToFind + tolerance;
24292696 for (int i = startIndex; i >= 0; i--) {
24302697 if (array[i] >= min && array[i] <= max) {
24312698 return i;
24432710 * @param valueToFind the value to find
24442711 * @return {@code true} if the array contains the object
24452712 */
2446 public static boolean contains(double[] array, double valueToFind) {
2713 public static boolean contains(final double[] array, final double valueToFind) {
24472714 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
24482715 }
24492716
24602727 * @param tolerance the array contains the tolerance of the search
24612728 * @return true if value falling within tolerance is in array
24622729 */
2463 public static boolean contains(double[] array, double valueToFind, double tolerance) {
2730 public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {
24642731 return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND;
24652732 }
24662733
24762743 * @return the index of the value within the array,
24772744 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
24782745 */
2479 public static int indexOf(float[] array, float valueToFind) {
2746 public static int indexOf(final float[] array, final float valueToFind) {
24802747 return indexOf(array, valueToFind, 0);
24812748 }
24822749
24942761 * @return the index of the value within the array,
24952762 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
24962763 */
2497 public static int indexOf(float[] array, float valueToFind, int startIndex) {
2764 public static int indexOf(final float[] array, final float valueToFind, int startIndex) {
24982765 if (ArrayUtils.isEmpty(array)) {
24992766 return INDEX_NOT_FOUND;
25002767 }
25192786 * @return the last index of the value within the array,
25202787 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
25212788 */
2522 public static int lastIndexOf(float[] array, float valueToFind) {
2789 public static int lastIndexOf(final float[] array, final float valueToFind) {
25232790 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
25242791 }
25252792
25372804 * @return the last index of the value within the array,
25382805 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
25392806 */
2540 public static int lastIndexOf(float[] array, float valueToFind, int startIndex) {
2807 public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {
25412808 if (ArrayUtils.isEmpty(array)) {
25422809 return INDEX_NOT_FOUND;
25432810 }
25632830 * @param valueToFind the value to find
25642831 * @return {@code true} if the array contains the object
25652832 */
2566 public static boolean contains(float[] array, float valueToFind) {
2833 public static boolean contains(final float[] array, final float valueToFind) {
25672834 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
25682835 }
25692836
25792846 * @return the index of the value within the array,
25802847 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
25812848 */
2582 public static int indexOf(boolean[] array, boolean valueToFind) {
2849 public static int indexOf(final boolean[] array, final boolean valueToFind) {
25832850 return indexOf(array, valueToFind, 0);
25842851 }
25852852
25982865 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null}
25992866 * array input
26002867 */
2601 public static int indexOf(boolean[] array, boolean valueToFind, int startIndex) {
2868 public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {
26022869 if (ArrayUtils.isEmpty(array)) {
26032870 return INDEX_NOT_FOUND;
26042871 }
26242891 * @return the last index of the value within the array,
26252892 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
26262893 */
2627 public static int lastIndexOf(boolean[] array, boolean valueToFind) {
2894 public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {
26282895 return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
26292896 }
26302897
26422909 * @return the last index of the value within the array,
26432910 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
26442911 */
2645 public static int lastIndexOf(boolean[] array, boolean valueToFind, int startIndex) {
2912 public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {
26462913 if (ArrayUtils.isEmpty(array)) {
26472914 return INDEX_NOT_FOUND;
26482915 }
26682935 * @param valueToFind the value to find
26692936 * @return {@code true} if the array contains the object
26702937 */
2671 public static boolean contains(boolean[] array, boolean valueToFind) {
2938 public static boolean contains(final boolean[] array, final boolean valueToFind) {
26722939 return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
26732940 }
26742941
26862953 * @return a {@code char} array, {@code null} if null array input
26872954 * @throws NullPointerException if array content is {@code null}
26882955 */
2689 public static char[] toPrimitive(Character[] array) {
2956 public static char[] toPrimitive(final Character[] array) {
26902957 if (array == null) {
26912958 return null;
26922959 } else if (array.length == 0) {
27082975 * @param valueForNull the value to insert if {@code null} found
27092976 * @return a {@code char} array, {@code null} if null array input
27102977 */
2711 public static char[] toPrimitive(Character[] array, char valueForNull) {
2978 public static char[] toPrimitive(final Character[] array, final char valueForNull) {
27122979 if (array == null) {
27132980 return null;
27142981 } else if (array.length == 0) {
27162983 }
27172984 final char[] result = new char[array.length];
27182985 for (int i = 0; i < array.length; i++) {
2719 Character b = array[i];
2986 final Character b = array[i];
27202987 result[i] = (b == null ? valueForNull : b.charValue());
27212988 }
27222989 return result;
27302997 * @param array a {@code char} array
27312998 * @return a {@code Character} array, {@code null} if null array input
27322999 */
2733 public static Character[] toObject(char[] array) {
3000 public static Character[] toObject(final char[] array) {
27343001 if (array == null) {
27353002 return null;
27363003 } else if (array.length == 0) {
27543021 * @return a {@code long} array, {@code null} if null array input
27553022 * @throws NullPointerException if array content is {@code null}
27563023 */
2757 public static long[] toPrimitive(Long[] array) {
3024 public static long[] toPrimitive(final Long[] array) {
27583025 if (array == null) {
27593026 return null;
27603027 } else if (array.length == 0) {
27763043 * @param valueForNull the value to insert if {@code null} found
27773044 * @return a {@code long} array, {@code null} if null array input
27783045 */
2779 public static long[] toPrimitive(Long[] array, long valueForNull) {
3046 public static long[] toPrimitive(final Long[] array, final long valueForNull) {
27803047 if (array == null) {
27813048 return null;
27823049 } else if (array.length == 0) {
27843051 }
27853052 final long[] result = new long[array.length];
27863053 for (int i = 0; i < array.length; i++) {
2787 Long b = array[i];
3054 final Long b = array[i];
27883055 result[i] = (b == null ? valueForNull : b.longValue());
27893056 }
27903057 return result;
27983065 * @param array a {@code long} array
27993066 * @return a {@code Long} array, {@code null} if null array input
28003067 */
2801 public static Long[] toObject(long[] array) {
3068 public static Long[] toObject(final long[] array) {
28023069 if (array == null) {
28033070 return null;
28043071 } else if (array.length == 0) {
28223089 * @return an {@code int} array, {@code null} if null array input
28233090 * @throws NullPointerException if array content is {@code null}
28243091 */
2825 public static int[] toPrimitive(Integer[] array) {
3092 public static int[] toPrimitive(final Integer[] array) {
28263093 if (array == null) {
28273094 return null;
28283095 } else if (array.length == 0) {
28443111 * @param valueForNull the value to insert if {@code null} found
28453112 * @return an {@code int} array, {@code null} if null array input
28463113 */
2847 public static int[] toPrimitive(Integer[] array, int valueForNull) {
3114 public static int[] toPrimitive(final Integer[] array, final int valueForNull) {
28483115 if (array == null) {
28493116 return null;
28503117 } else if (array.length == 0) {
28523119 }
28533120 final int[] result = new int[array.length];
28543121 for (int i = 0; i < array.length; i++) {
2855 Integer b = array[i];
3122 final Integer b = array[i];
28563123 result[i] = (b == null ? valueForNull : b.intValue());
28573124 }
28583125 return result;
28663133 * @param array an {@code int} array
28673134 * @return an {@code Integer} array, {@code null} if null array input
28683135 */
2869 public static Integer[] toObject(int[] array) {
3136 public static Integer[] toObject(final int[] array) {
28703137 if (array == null) {
28713138 return null;
28723139 } else if (array.length == 0) {
28903157 * @return a {@code byte} array, {@code null} if null array input
28913158 * @throws NullPointerException if array content is {@code null}
28923159 */
2893 public static short[] toPrimitive(Short[] array) {
3160 public static short[] toPrimitive(final Short[] array) {
28943161 if (array == null) {
28953162 return null;
28963163 } else if (array.length == 0) {
29123179 * @param valueForNull the value to insert if {@code null} found
29133180 * @return a {@code byte} array, {@code null} if null array input
29143181 */
2915 public static short[] toPrimitive(Short[] array, short valueForNull) {
3182 public static short[] toPrimitive(final Short[] array, final short valueForNull) {
29163183 if (array == null) {
29173184 return null;
29183185 } else if (array.length == 0) {
29203187 }
29213188 final short[] result = new short[array.length];
29223189 for (int i = 0; i < array.length; i++) {
2923 Short b = array[i];
3190 final Short b = array[i];
29243191 result[i] = (b == null ? valueForNull : b.shortValue());
29253192 }
29263193 return result;
29343201 * @param array a {@code short} array
29353202 * @return a {@code Short} array, {@code null} if null array input
29363203 */
2937 public static Short[] toObject(short[] array) {
3204 public static Short[] toObject(final short[] array) {
29383205 if (array == null) {
29393206 return null;
29403207 } else if (array.length == 0) {
29583225 * @return a {@code byte} array, {@code null} if null array input
29593226 * @throws NullPointerException if array content is {@code null}
29603227 */
2961 public static byte[] toPrimitive(Byte[] array) {
3228 public static byte[] toPrimitive(final Byte[] array) {
29623229 if (array == null) {
29633230 return null;
29643231 } else if (array.length == 0) {
29803247 * @param valueForNull the value to insert if {@code null} found
29813248 * @return a {@code byte} array, {@code null} if null array input
29823249 */
2983 public static byte[] toPrimitive(Byte[] array, byte valueForNull) {
3250 public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {
29843251 if (array == null) {
29853252 return null;
29863253 } else if (array.length == 0) {
29883255 }
29893256 final byte[] result = new byte[array.length];
29903257 for (int i = 0; i < array.length; i++) {
2991 Byte b = array[i];
3258 final Byte b = array[i];
29923259 result[i] = (b == null ? valueForNull : b.byteValue());
29933260 }
29943261 return result;
30023269 * @param array a {@code byte} array
30033270 * @return a {@code Byte} array, {@code null} if null array input
30043271 */
3005 public static Byte[] toObject(byte[] array) {
3272 public static Byte[] toObject(final byte[] array) {
30063273 if (array == null) {
30073274 return null;
30083275 } else if (array.length == 0) {
30263293 * @return a {@code double} array, {@code null} if null array input
30273294 * @throws NullPointerException if array content is {@code null}
30283295 */
3029 public static double[] toPrimitive(Double[] array) {
3296 public static double[] toPrimitive(final Double[] array) {
30303297 if (array == null) {
30313298 return null;
30323299 } else if (array.length == 0) {
30483315 * @param valueForNull the value to insert if {@code null} found
30493316 * @return a {@code double} array, {@code null} if null array input
30503317 */
3051 public static double[] toPrimitive(Double[] array, double valueForNull) {
3318 public static double[] toPrimitive(final Double[] array, final double valueForNull) {
30523319 if (array == null) {
30533320 return null;
30543321 } else if (array.length == 0) {
30563323 }
30573324 final double[] result = new double[array.length];
30583325 for (int i = 0; i < array.length; i++) {
3059 Double b = array[i];
3326 final Double b = array[i];
30603327 result[i] = (b == null ? valueForNull : b.doubleValue());
30613328 }
30623329 return result;
30703337 * @param array a {@code double} array
30713338 * @return a {@code Double} array, {@code null} if null array input
30723339 */
3073 public static Double[] toObject(double[] array) {
3340 public static Double[] toObject(final double[] array) {
30743341 if (array == null) {
30753342 return null;
30763343 } else if (array.length == 0) {
30943361 * @return a {@code float} array, {@code null} if null array input
30953362 * @throws NullPointerException if array content is {@code null}
30963363 */
3097 public static float[] toPrimitive(Float[] array) {
3364 public static float[] toPrimitive(final Float[] array) {
30983365 if (array == null) {
30993366 return null;
31003367 } else if (array.length == 0) {
31163383 * @param valueForNull the value to insert if {@code null} found
31173384 * @return a {@code float} array, {@code null} if null array input
31183385 */
3119 public static float[] toPrimitive(Float[] array, float valueForNull) {
3386 public static float[] toPrimitive(final Float[] array, final float valueForNull) {
31203387 if (array == null) {
31213388 return null;
31223389 } else if (array.length == 0) {
31243391 }
31253392 final float[] result = new float[array.length];
31263393 for (int i = 0; i < array.length; i++) {
3127 Float b = array[i];
3394 final Float b = array[i];
31283395 result[i] = (b == null ? valueForNull : b.floatValue());
31293396 }
31303397 return result;
31383405 * @param array a {@code float} array
31393406 * @return a {@code Float} array, {@code null} if null array input
31403407 */
3141 public static Float[] toObject(float[] array) {
3408 public static Float[] toObject(final float[] array) {
31423409 if (array == null) {
31433410 return null;
31443411 } else if (array.length == 0) {
31623429 * @return a {@code boolean} array, {@code null} if null array input
31633430 * @throws NullPointerException if array content is {@code null}
31643431 */
3165 public static boolean[] toPrimitive(Boolean[] array) {
3432 public static boolean[] toPrimitive(final Boolean[] array) {
31663433 if (array == null) {
31673434 return null;
31683435 } else if (array.length == 0) {
31843451 * @param valueForNull the value to insert if {@code null} found
31853452 * @return a {@code boolean} array, {@code null} if null array input
31863453 */
3187 public static boolean[] toPrimitive(Boolean[] array, boolean valueForNull) {
3454 public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {
31883455 if (array == null) {
31893456 return null;
31903457 } else if (array.length == 0) {
31923459 }
31933460 final boolean[] result = new boolean[array.length];
31943461 for (int i = 0; i < array.length; i++) {
3195 Boolean b = array[i];
3462 final Boolean b = array[i];
31963463 result[i] = (b == null ? valueForNull : b.booleanValue());
31973464 }
31983465 return result;
32063473 * @param array a {@code boolean} array
32073474 * @return a {@code Boolean} array, {@code null} if null array input
32083475 */
3209 public static Boolean[] toObject(boolean[] array) {
3476 public static Boolean[] toObject(final boolean[] array) {
32103477 if (array == null) {
32113478 return null;
32123479 } else if (array.length == 0) {
32273494 * @return {@code true} if the array is empty or {@code null}
32283495 * @since 2.1
32293496 */
3230 public static boolean isEmpty(Object[] array) {
3497 public static boolean isEmpty(final Object[] array) {
32313498 return array == null || array.length == 0;
32323499 }
32333500
32383505 * @return {@code true} if the array is empty or {@code null}
32393506 * @since 2.1
32403507 */
3241 public static boolean isEmpty(long[] array) {
3508 public static boolean isEmpty(final long[] array) {
32423509 return array == null || array.length == 0;
32433510 }
32443511
32493516 * @return {@code true} if the array is empty or {@code null}
32503517 * @since 2.1
32513518 */
3252 public static boolean isEmpty(int[] array) {
3519 public static boolean isEmpty(final int[] array) {
32533520 return array == null || array.length == 0;
32543521 }
32553522
32603527 * @return {@code true} if the array is empty or {@code null}
32613528 * @since 2.1
32623529 */
3263 public static boolean isEmpty(short[] array) {
3530 public static boolean isEmpty(final short[] array) {
32643531 return array == null || array.length == 0;
32653532 }
32663533
32713538 * @return {@code true} if the array is empty or {@code null}
32723539 * @since 2.1
32733540 */
3274 public static boolean isEmpty(char[] array) {
3541 public static boolean isEmpty(final char[] array) {
32753542 return array == null || array.length == 0;
32763543 }
32773544
32823549 * @return {@code true} if the array is empty or {@code null}
32833550 * @since 2.1
32843551 */
3285 public static boolean isEmpty(byte[] array) {
3552 public static boolean isEmpty(final byte[] array) {
32863553 return array == null || array.length == 0;
32873554 }
32883555
32933560 * @return {@code true} if the array is empty or {@code null}
32943561 * @since 2.1
32953562 */
3296 public static boolean isEmpty(double[] array) {
3563 public static boolean isEmpty(final double[] array) {
32973564 return array == null || array.length == 0;
32983565 }
32993566
33043571 * @return {@code true} if the array is empty or {@code null}
33053572 * @since 2.1
33063573 */
3307 public static boolean isEmpty(float[] array) {
3574 public static boolean isEmpty(final float[] array) {
33083575 return array == null || array.length == 0;
33093576 }
33103577
33153582 * @return {@code true} if the array is empty or {@code null}
33163583 * @since 2.1
33173584 */
3318 public static boolean isEmpty(boolean[] array) {
3585 public static boolean isEmpty(final boolean[] array) {
33193586 return array == null || array.length == 0;
33203587 }
33213588
33283595 * @return {@code true} if the array is not empty or not {@code null}
33293596 * @since 2.5
33303597 */
3331 public static <T> boolean isNotEmpty(T[] array) {
3598 public static <T> boolean isNotEmpty(final T[] array) {
33323599 return (array != null && array.length != 0);
33333600 }
33343601
33393606 * @return {@code true} if the array is not empty or not {@code null}
33403607 * @since 2.5
33413608 */
3342 public static boolean isNotEmpty(long[] array) {
3609 public static boolean isNotEmpty(final long[] array) {
33433610 return (array != null && array.length != 0);
33443611 }
33453612
33503617 * @return {@code true} if the array is not empty or not {@code null}
33513618 * @since 2.5
33523619 */
3353 public static boolean isNotEmpty(int[] array) {
3620 public static boolean isNotEmpty(final int[] array) {
33543621 return (array != null && array.length != 0);
33553622 }
33563623
33613628 * @return {@code true} if the array is not empty or not {@code null}
33623629 * @since 2.5
33633630 */
3364 public static boolean isNotEmpty(short[] array) {
3631 public static boolean isNotEmpty(final short[] array) {
33653632 return (array != null && array.length != 0);
33663633 }
33673634
33723639 * @return {@code true} if the array is not empty or not {@code null}
33733640 * @since 2.5
33743641 */
3375 public static boolean isNotEmpty(char[] array) {
3642 public static boolean isNotEmpty(final char[] array) {
33763643 return (array != null && array.length != 0);
33773644 }
33783645
33833650 * @return {@code true} if the array is not empty or not {@code null}
33843651 * @since 2.5
33853652 */
3386 public static boolean isNotEmpty(byte[] array) {
3653 public static boolean isNotEmpty(final byte[] array) {
33873654 return (array != null && array.length != 0);
33883655 }
33893656
33943661 * @return {@code true} if the array is not empty or not {@code null}
33953662 * @since 2.5
33963663 */
3397 public static boolean isNotEmpty(double[] array) {
3664 public static boolean isNotEmpty(final double[] array) {
33983665 return (array != null && array.length != 0);
33993666 }
34003667
34053672 * @return {@code true} if the array is not empty or not {@code null}
34063673 * @since 2.5
34073674 */
3408 public static boolean isNotEmpty(float[] array) {
3675 public static boolean isNotEmpty(final float[] array) {
34093676 return (array != null && array.length != 0);
34103677 }
34113678
34163683 * @return {@code true} if the array is not empty or not {@code null}
34173684 * @since 2.5
34183685 */
3419 public static boolean isNotEmpty(boolean[] array) {
3686 public static boolean isNotEmpty(final boolean[] array) {
34203687 return (array != null && array.length != 0);
34213688 }
34223689
34443711 * @since 2.1
34453712 * @throws IllegalArgumentException if the array types are incompatible
34463713 */
3447 public static <T> T[] addAll(T[] array1, T... array2) {
3714 public static <T> T[] addAll(final T[] array1, final T... array2) {
34483715 if (array1 == null) {
34493716 return clone(array2);
34503717 } else if (array2 == null) {
34523719 }
34533720 final Class<?> type1 = array1.getClass().getComponentType();
34543721 @SuppressWarnings("unchecked") // OK, because array is of type T
3722 final
34553723 T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
34563724 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
34573725 try {
34583726 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
3459 } catch (ArrayStoreException ase) {
3727 } catch (final ArrayStoreException ase) {
34603728 // Check if problem was due to incompatible types
34613729 /*
34623730 * We do this here, rather than before the copy because:
34903758 * @return The new boolean[] array.
34913759 * @since 2.1
34923760 */
3493 public static boolean[] addAll(boolean[] array1, boolean... array2) {
3761 public static boolean[] addAll(final boolean[] array1, final boolean... array2) {
34943762 if (array1 == null) {
34953763 return clone(array2);
34963764 } else if (array2 == null) {
34973765 return clone(array1);
34983766 }
3499 boolean[] joinedArray = new boolean[array1.length + array2.length];
3767 final boolean[] joinedArray = new boolean[array1.length + array2.length];
35003768 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
35013769 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
35023770 return joinedArray;
35193787 * @return The new char[] array.
35203788 * @since 2.1
35213789 */
3522 public static char[] addAll(char[] array1, char... array2) {
3790 public static char[] addAll(final char[] array1, final char... array2) {
35233791 if (array1 == null) {
35243792 return clone(array2);
35253793 } else if (array2 == null) {
35263794 return clone(array1);
35273795 }
3528 char[] joinedArray = new char[array1.length + array2.length];
3796 final char[] joinedArray = new char[array1.length + array2.length];
35293797 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
35303798 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
35313799 return joinedArray;
35483816 * @return The new byte[] array.
35493817 * @since 2.1
35503818 */
3551 public static byte[] addAll(byte[] array1, byte... array2) {
3819 public static byte[] addAll(final byte[] array1, final byte... array2) {
35523820 if (array1 == null) {
35533821 return clone(array2);
35543822 } else if (array2 == null) {
35553823 return clone(array1);
35563824 }
3557 byte[] joinedArray = new byte[array1.length + array2.length];
3825 final byte[] joinedArray = new byte[array1.length + array2.length];
35583826 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
35593827 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
35603828 return joinedArray;
35773845 * @return The new short[] array.
35783846 * @since 2.1
35793847 */
3580 public static short[] addAll(short[] array1, short... array2) {
3848 public static short[] addAll(final short[] array1, final short... array2) {
35813849 if (array1 == null) {
35823850 return clone(array2);
35833851 } else if (array2 == null) {
35843852 return clone(array1);
35853853 }
3586 short[] joinedArray = new short[array1.length + array2.length];
3854 final short[] joinedArray = new short[array1.length + array2.length];
35873855 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
35883856 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
35893857 return joinedArray;
36063874 * @return The new int[] array.
36073875 * @since 2.1
36083876 */
3609 public static int[] addAll(int[] array1, int... array2) {
3877 public static int[] addAll(final int[] array1, final int... array2) {
36103878 if (array1 == null) {
36113879 return clone(array2);
36123880 } else if (array2 == null) {
36133881 return clone(array1);
36143882 }
3615 int[] joinedArray = new int[array1.length + array2.length];
3883 final int[] joinedArray = new int[array1.length + array2.length];
36163884 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
36173885 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
36183886 return joinedArray;
36353903 * @return The new long[] array.
36363904 * @since 2.1
36373905 */
3638 public static long[] addAll(long[] array1, long... array2) {
3906 public static long[] addAll(final long[] array1, final long... array2) {
36393907 if (array1 == null) {
36403908 return clone(array2);
36413909 } else if (array2 == null) {
36423910 return clone(array1);
36433911 }
3644 long[] joinedArray = new long[array1.length + array2.length];
3912 final long[] joinedArray = new long[array1.length + array2.length];
36453913 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
36463914 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
36473915 return joinedArray;
36643932 * @return The new float[] array.
36653933 * @since 2.1
36663934 */
3667 public static float[] addAll(float[] array1, float... array2) {
3935 public static float[] addAll(final float[] array1, final float... array2) {
36683936 if (array1 == null) {
36693937 return clone(array2);
36703938 } else if (array2 == null) {
36713939 return clone(array1);
36723940 }
3673 float[] joinedArray = new float[array1.length + array2.length];
3941 final float[] joinedArray = new float[array1.length + array2.length];
36743942 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
36753943 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
36763944 return joinedArray;
36933961 * @return The new double[] array.
36943962 * @since 2.1
36953963 */
3696 public static double[] addAll(double[] array1, double... array2) {
3964 public static double[] addAll(final double[] array1, final double... array2) {
36973965 if (array1 == null) {
36983966 return clone(array2);
36993967 } else if (array2 == null) {
37003968 return clone(array1);
37013969 }
3702 double[] joinedArray = new double[array1.length + array2.length];
3970 final double[] joinedArray = new double[array1.length + array2.length];
37033971 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
37043972 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
37053973 return joinedArray;
37344002 * @since 2.1
37354003 * @throws IllegalArgumentException if both arguments are null
37364004 */
3737 public static <T> T[] add(T[] array, T element) {
4005 public static <T> T[] add(final T[] array, final T element) {
37384006 Class<?> type;
37394007 if (array != null){
37404008 type = array.getClass();
37444012 throw new IllegalArgumentException("Arguments cannot both be null");
37454013 }
37464014 @SuppressWarnings("unchecked") // type must be T
4015 final
37474016 T[] newArray = (T[]) copyArrayGrow1(array, type);
37484017 newArray[newArray.length - 1] = element;
37494018 return newArray;
37704039 * @return A new array containing the existing elements plus the new element
37714040 * @since 2.1
37724041 */
3773 public static boolean[] add(boolean[] array, boolean element) {
3774 boolean[] newArray = (boolean[])copyArrayGrow1(array, Boolean.TYPE);
4042 public static boolean[] add(final boolean[] array, final boolean element) {
4043 final boolean[] newArray = (boolean[])copyArrayGrow1(array, Boolean.TYPE);
37754044 newArray[newArray.length - 1] = element;
37764045 return newArray;
37774046 }
37974066 * @return A new array containing the existing elements plus the new element
37984067 * @since 2.1
37994068 */
3800 public static byte[] add(byte[] array, byte element) {
3801 byte[] newArray = (byte[])copyArrayGrow1(array, Byte.TYPE);
4069 public static byte[] add(final byte[] array, final byte element) {
4070 final byte[] newArray = (byte[])copyArrayGrow1(array, Byte.TYPE);
38024071 newArray[newArray.length - 1] = element;
38034072 return newArray;
38044073 }
38244093 * @return A new array containing the existing elements plus the new element
38254094 * @since 2.1
38264095 */
3827 public static char[] add(char[] array, char element) {
3828 char[] newArray = (char[])copyArrayGrow1(array, Character.TYPE);
4096 public static char[] add(final char[] array, final char element) {
4097 final char[] newArray = (char[])copyArrayGrow1(array, Character.TYPE);
38294098 newArray[newArray.length - 1] = element;
38304099 return newArray;
38314100 }
38514120 * @return A new array containing the existing elements plus the new element
38524121 * @since 2.1
38534122 */
3854 public static double[] add(double[] array, double element) {
3855 double[] newArray = (double[])copyArrayGrow1(array, Double.TYPE);
4123 public static double[] add(final double[] array, final double element) {
4124 final double[] newArray = (double[])copyArrayGrow1(array, Double.TYPE);
38564125 newArray[newArray.length - 1] = element;
38574126 return newArray;
38584127 }
38784147 * @return A new array containing the existing elements plus the new element
38794148 * @since 2.1
38804149 */
3881 public static float[] add(float[] array, float element) {
3882 float[] newArray = (float[])copyArrayGrow1(array, Float.TYPE);
4150 public static float[] add(final float[] array, final float element) {
4151 final float[] newArray = (float[])copyArrayGrow1(array, Float.TYPE);
38834152 newArray[newArray.length - 1] = element;
38844153 return newArray;
38854154 }
39054174 * @return A new array containing the existing elements plus the new element
39064175 * @since 2.1
39074176 */
3908 public static int[] add(int[] array, int element) {
3909 int[] newArray = (int[])copyArrayGrow1(array, Integer.TYPE);
4177 public static int[] add(final int[] array, final int element) {
4178 final int[] newArray = (int[])copyArrayGrow1(array, Integer.TYPE);
39104179 newArray[newArray.length - 1] = element;
39114180 return newArray;
39124181 }
39324201 * @return A new array containing the existing elements plus the new element
39334202 * @since 2.1
39344203 */
3935 public static long[] add(long[] array, long element) {
3936 long[] newArray = (long[])copyArrayGrow1(array, Long.TYPE);
4204 public static long[] add(final long[] array, final long element) {
4205 final long[] newArray = (long[])copyArrayGrow1(array, Long.TYPE);
39374206 newArray[newArray.length - 1] = element;
39384207 return newArray;
39394208 }
39594228 * @return A new array containing the existing elements plus the new element
39604229 * @since 2.1
39614230 */
3962 public static short[] add(short[] array, short element) {
3963 short[] newArray = (short[])copyArrayGrow1(array, Short.TYPE);
4231 public static short[] add(final short[] array, final short element) {
4232 final short[] newArray = (short[])copyArrayGrow1(array, Short.TYPE);
39644233 newArray[newArray.length - 1] = element;
39654234 return newArray;
39664235 }
39744243 * size 1 array of this type.
39754244 * @return A new copy of the array of size 1 greater than the input.
39764245 */
3977 private static Object copyArrayGrow1(Object array, Class<?> newArrayComponentType) {
4246 private static Object copyArrayGrow1(final Object array, final Class<?> newArrayComponentType) {
39784247 if (array != null) {
3979 int arrayLength = Array.getLength(array);
3980 Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
4248 final int arrayLength = Array.getLength(array);
4249 final Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
39814250 System.arraycopy(array, 0, newArray, 0, arrayLength);
39824251 return newArray;
39834252 }
40144283 * (index < 0 || index > array.length).
40154284 * @throws IllegalArgumentException if both array and element are null
40164285 */
4017 public static <T> T[] add(T[] array, int index, T element) {
4286 public static <T> T[] add(final T[] array, final int index, final T element) {
40184287 Class<?> clss = null;
40194288 if (array != null) {
40204289 clss = array.getClass().getComponentType();
40554324 * @throws IndexOutOfBoundsException if the index is out of range
40564325 * (index < 0 || index > array.length).
40574326 */
4058 public static boolean[] add(boolean[] array, int index, boolean element) {
4327 public static boolean[] add(final boolean[] array, final int index, final boolean element) {
40594328 return (boolean[]) add(array, index, Boolean.valueOf(element), Boolean.TYPE);
40604329 }
40614330
40874356 * @throws IndexOutOfBoundsException if the index is out of range
40884357 * (index < 0 || index > array.length).
40894358 */
4090 public static char[] add(char[] array, int index, char element) {
4359 public static char[] add(final char[] array, final int index, final char element) {
40914360 return (char[]) add(array, index, Character.valueOf(element), Character.TYPE);
40924361 }
40934362
41184387 * @throws IndexOutOfBoundsException if the index is out of range
41194388 * (index < 0 || index > array.length).
41204389 */
4121 public static byte[] add(byte[] array, int index, byte element) {
4390 public static byte[] add(final byte[] array, final int index, final byte element) {
41224391 return (byte[]) add(array, index, Byte.valueOf(element), Byte.TYPE);
41234392 }
41244393
41494418 * @throws IndexOutOfBoundsException if the index is out of range
41504419 * (index < 0 || index > array.length).
41514420 */
4152 public static short[] add(short[] array, int index, short element) {
4421 public static short[] add(final short[] array, final int index, final short element) {
41534422 return (short[]) add(array, index, Short.valueOf(element), Short.TYPE);
41544423 }
41554424
41804449 * @throws IndexOutOfBoundsException if the index is out of range
41814450 * (index < 0 || index > array.length).
41824451 */
4183 public static int[] add(int[] array, int index, int element) {
4452 public static int[] add(final int[] array, final int index, final int element) {
41844453 return (int[]) add(array, index, Integer.valueOf(element), Integer.TYPE);
41854454 }
41864455
42114480 * @throws IndexOutOfBoundsException if the index is out of range
42124481 * (index < 0 || index > array.length).
42134482 */
4214 public static long[] add(long[] array, int index, long element) {
4483 public static long[] add(final long[] array, final int index, final long element) {
42154484 return (long[]) add(array, index, Long.valueOf(element), Long.TYPE);
42164485 }
42174486
42424511 * @throws IndexOutOfBoundsException if the index is out of range
42434512 * (index < 0 || index > array.length).
42444513 */
4245 public static float[] add(float[] array, int index, float element) {
4514 public static float[] add(final float[] array, final int index, final float element) {
42464515 return (float[]) add(array, index, Float.valueOf(element), Float.TYPE);
42474516 }
42484517
42734542 * @throws IndexOutOfBoundsException if the index is out of range
42744543 * (index < 0 || index > array.length).
42754544 */
4276 public static double[] add(double[] array, int index, double element) {
4545 public static double[] add(final double[] array, final int index, final double element) {
42774546 return (double[]) add(array, index, Double.valueOf(element), Double.TYPE);
42784547 }
42794548
42884557 * @param clss the type of the element being added
42894558 * @return A new array containing the existing elements and the new element
42904559 */
4291 private static Object add(Object array, int index, Object element, Class<?> clss) {
4560 private static Object add(final Object array, final int index, final Object element, final Class<?> clss) {
42924561 if (array == null) {
42934562 if (index != 0) {
42944563 throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
42954564 }
4296 Object joinedArray = Array.newInstance(clss, 1);
4565 final Object joinedArray = Array.newInstance(clss, 1);
42974566 Array.set(joinedArray, 0, element);
42984567 return joinedArray;
42994568 }
4300 int length = Array.getLength(array);
4569 final int length = Array.getLength(array);
43014570 if (index > length || index < 0) {
43024571 throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
43034572 }
4304 Object result = Array.newInstance(clss, length + 1);
4573 final Object result = Array.newInstance(clss, length + 1);
43054574 System.arraycopy(array, 0, result, 0, index);
43064575 Array.set(result, index, element);
43074576 if (index < length) {
43404609 * @since 2.1
43414610 */
43424611 @SuppressWarnings("unchecked") // remove() always creates an array of the same type as its input
4343 public static <T> T[] remove(T[] array, int index) {
4612 public static <T> T[] remove(final T[] array, final int index) {
43444613 return (T[]) remove((Object) array, index);
43454614 }
43464615
43704639 * occurrence of the specified element.
43714640 * @since 2.1
43724641 */
4373 public static <T> T[] removeElement(T[] array, Object element) {
4374 int index = indexOf(array, element);
4642 public static <T> T[] removeElement(final T[] array, final Object element) {
4643 final int index = indexOf(array, element);
43754644 if (index == INDEX_NOT_FOUND) {
43764645 return clone(array);
43774646 }
44064675 * (index < 0 || index >= array.length), or if the array is {@code null}.
44074676 * @since 2.1
44084677 */
4409 public static boolean[] remove(boolean[] array, int index) {
4678 public static boolean[] remove(final boolean[] array, final int index) {
44104679 return (boolean[]) remove((Object) array, index);
44114680 }
44124681
44354704 * occurrence of the specified element.
44364705 * @since 2.1
44374706 */
4438 public static boolean[] removeElement(boolean[] array, boolean element) {
4439 int index = indexOf(array, element);
4707 public static boolean[] removeElement(final boolean[] array, final boolean element) {
4708 final int index = indexOf(array, element);
44404709 if (index == INDEX_NOT_FOUND) {
44414710 return clone(array);
44424711 }
44714740 * (index < 0 || index >= array.length), or if the array is {@code null}.
44724741 * @since 2.1
44734742 */
4474 public static byte[] remove(byte[] array, int index) {
4743 public static byte[] remove(final byte[] array, final int index) {
44754744 return (byte[]) remove((Object) array, index);
44764745 }
44774746
45004769 * occurrence of the specified element.
45014770 * @since 2.1
45024771 */
4503 public static byte[] removeElement(byte[] array, byte element) {
4504 int index = indexOf(array, element);
4772 public static byte[] removeElement(final byte[] array, final byte element) {
4773 final int index = indexOf(array, element);
45054774 if (index == INDEX_NOT_FOUND) {
45064775 return clone(array);
45074776 }
45364805 * (index < 0 || index >= array.length), or if the array is {@code null}.
45374806 * @since 2.1
45384807 */
4539 public static char[] remove(char[] array, int index) {
4808 public static char[] remove(final char[] array, final int index) {
45404809 return (char[]) remove((Object) array, index);
45414810 }
45424811
45654834 * occurrence of the specified element.
45664835 * @since 2.1
45674836 */
4568 public static char[] removeElement(char[] array, char element) {
4569 int index = indexOf(array, element);
4837 public static char[] removeElement(final char[] array, final char element) {
4838 final int index = indexOf(array, element);
45704839 if (index == INDEX_NOT_FOUND) {
45714840 return clone(array);
45724841 }
46014870 * (index < 0 || index >= array.length), or if the array is {@code null}.
46024871 * @since 2.1
46034872 */
4604 public static double[] remove(double[] array, int index) {
4873 public static double[] remove(final double[] array, final int index) {
46054874 return (double[]) remove((Object) array, index);
46064875 }
46074876
46304899 * occurrence of the specified element.
46314900 * @since 2.1
46324901 */
4633 public static double[] removeElement(double[] array, double element) {
4634 int index = indexOf(array, element);
4902 public static double[] removeElement(final double[] array, final double element) {
4903 final int index = indexOf(array, element);
46354904 if (index == INDEX_NOT_FOUND) {
46364905 return clone(array);
46374906 }
46664935 * (index < 0 || index >= array.length), or if the array is {@code null}.
46674936 * @since 2.1
46684937 */
4669 public static float[] remove(float[] array, int index) {
4938 public static float[] remove(final float[] array, final int index) {
46704939 return (float[]) remove((Object) array, index);
46714940 }
46724941
46954964 * occurrence of the specified element.
46964965 * @since 2.1
46974966 */
4698 public static float[] removeElement(float[] array, float element) {
4699 int index = indexOf(array, element);
4967 public static float[] removeElement(final float[] array, final float element) {
4968 final int index = indexOf(array, element);
47004969 if (index == INDEX_NOT_FOUND) {
47014970 return clone(array);
47024971 }
47315000 * (index < 0 || index >= array.length), or if the array is {@code null}.
47325001 * @since 2.1
47335002 */
4734 public static int[] remove(int[] array, int index) {
5003 public static int[] remove(final int[] array, final int index) {
47355004 return (int[]) remove((Object) array, index);
47365005 }
47375006
47605029 * occurrence of the specified element.
47615030 * @since 2.1
47625031 */
4763 public static int[] removeElement(int[] array, int element) {
4764 int index = indexOf(array, element);
5032 public static int[] removeElement(final int[] array, final int element) {
5033 final int index = indexOf(array, element);
47655034 if (index == INDEX_NOT_FOUND) {
47665035 return clone(array);
47675036 }
47965065 * (index < 0 || index >= array.length), or if the array is {@code null}.
47975066 * @since 2.1
47985067 */
4799 public static long[] remove(long[] array, int index) {
5068 public static long[] remove(final long[] array, final int index) {
48005069 return (long[]) remove((Object) array, index);
48015070 }
48025071
48255094 * occurrence of the specified element.
48265095 * @since 2.1
48275096 */
4828 public static long[] removeElement(long[] array, long element) {
4829 int index = indexOf(array, element);
5097 public static long[] removeElement(final long[] array, final long element) {
5098 final int index = indexOf(array, element);
48305099 if (index == INDEX_NOT_FOUND) {
48315100 return clone(array);
48325101 }
48615130 * (index < 0 || index >= array.length), or if the array is {@code null}.
48625131 * @since 2.1
48635132 */
4864 public static short[] remove(short[] array, int index) {
5133 public static short[] remove(final short[] array, final int index) {
48655134 return (short[]) remove((Object) array, index);
48665135 }
48675136
48905159 * occurrence of the specified element.
48915160 * @since 2.1
48925161 */
4893 public static short[] removeElement(short[] array, short element) {
4894 int index = indexOf(array, element);
5162 public static short[] removeElement(final short[] array, final short element) {
5163 final int index = indexOf(array, element);
48955164 if (index == INDEX_NOT_FOUND) {
48965165 return clone(array);
48975166 }
49195188 * (index < 0 || index >= array.length), or if the array is {@code null}.
49205189 * @since 2.1
49215190 */
4922 private static Object remove(Object array, int index) {
4923 int length = getLength(array);
5191 private static Object remove(final Object array, final int index) {
5192 final int length = getLength(array);
49245193 if (index < 0 || index >= length) {
49255194 throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
49265195 }
49275196
4928 Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
5197 final Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
49295198 System.arraycopy(array, 0, result, 0, index);
49305199 if (index < length - 1) {
49315200 System.arraycopy(array, index + 1, result, index, length - index - 1);
49605229 * (index < 0 || index >= array.length), or if the array is {@code null}.
49615230 * @since 3.0.1
49625231 */
4963 @SuppressWarnings("unchecked")
4964 // removeAll() always creates an array of the same type as its input
4965 public static <T> T[] removeAll(T[] array, int... indices) {
5232 @SuppressWarnings("unchecked") // removeAll() always creates an array of the same type as its input
5233 public static <T> T[] removeAll(final T[] array, final int... indices) {
49665234 return (T[]) removeAll((Object) array, clone(indices));
49675235 }
49685236
49945262 * earliest-encountered occurrences of the specified elements.
49955263 * @since 3.0.1
49965264 */
4997 public static <T> T[] removeElements(T[] array, T... values) {
5265 public static <T> T[] removeElements(final T[] array, final T... values) {
49985266 if (isEmpty(array) || isEmpty(values)) {
49995267 return clone(array);
50005268 }
5001 HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(values.length);
5002 for (T v : values) {
5003 MutableInt count = occurrences.get(v);
5269 final HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(values.length);
5270 for (final T v : values) {
5271 final MutableInt count = occurrences.get(v);
50045272 if (count == null) {
50055273 occurrences.put(v, new MutableInt(1));
50065274 } else {
50075275 count.increment();
50085276 }
50095277 }
5010 HashSet<Integer> toRemove = new HashSet<Integer>();
5011 for (Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
5012 T v = e.getKey();
5278 final BitSet toRemove = new BitSet();
5279 for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
5280 final T v = e.getKey();
50135281 int found = 0;
50145282 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
50155283 found = indexOf(array, v, found);
50165284 if (found < 0) {
50175285 break;
50185286 }
5019 toRemove.add(found++);
5287 toRemove.set(found++);
50205288 }
50215289 }
5022 return removeAll(array, extractIndices(toRemove));
5290 @SuppressWarnings("unchecked") // removeAll() always creates an array of the same type as its input
5291 final
5292 T[] result = (T[]) removeAll(array, toRemove);
5293 return result;
50235294 }
50245295
50255296 /**
50515322 * (index < 0 || index >= array.length), or if the array is {@code null}.
50525323 * @since 3.0.1
50535324 */
5054 public static byte[] removeAll(byte[] array, int... indices) {
5325 public static byte[] removeAll(final byte[] array, final int... indices) {
50555326 return (byte[]) removeAll((Object) array, clone(indices));
50565327 }
50575328
50825353 * earliest-encountered occurrences of the specified elements.
50835354 * @since 3.0.1
50845355 */
5085 public static byte[] removeElements(byte[] array, byte... values) {
5356 public static byte[] removeElements(final byte[] array, final byte... values) {
50865357 if (isEmpty(array) || isEmpty(values)) {
50875358 return clone(array);
50885359 }
5089 HashMap<Byte, MutableInt> occurrences = new HashMap<Byte, MutableInt>(values.length);
5090 for (byte v : values) {
5091 Byte boxed = Byte.valueOf(v);
5092 MutableInt count = occurrences.get(boxed);
5360 final HashMap<Byte, MutableInt> occurrences = new HashMap<Byte, MutableInt>(values.length);
5361 for (final byte v : values) {
5362 final Byte boxed = Byte.valueOf(v);
5363 final MutableInt count = occurrences.get(boxed);
50935364 if (count == null) {
50945365 occurrences.put(boxed, new MutableInt(1));
50955366 } else {
50965367 count.increment();
50975368 }
50985369 }
5099 HashSet<Integer> toRemove = new HashSet<Integer>();
5100 for (Map.Entry<Byte, MutableInt> e : occurrences.entrySet()) {
5101 Byte v = e.getKey();
5370 final BitSet toRemove = new BitSet();
5371 for (final Map.Entry<Byte, MutableInt> e : occurrences.entrySet()) {
5372 final Byte v = e.getKey();
51025373 int found = 0;
51035374 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
51045375 found = indexOf(array, v.byteValue(), found);
51055376 if (found < 0) {
51065377 break;
51075378 }
5108 toRemove.add(found++);
5379 toRemove.set(found++);
51095380 }
51105381 }
5111 return removeAll(array, extractIndices(toRemove));
5382 return (byte[]) removeAll(array, toRemove);
51125383 }
51135384
51145385 /**
51405411 * (index < 0 || index >= array.length), or if the array is {@code null}.
51415412 * @since 3.0.1
51425413 */
5143 public static short[] removeAll(short[] array, int... indices) {
5414 public static short[] removeAll(final short[] array, final int... indices) {
51445415 return (short[]) removeAll((Object) array, clone(indices));
51455416 }
51465417
51715442 * earliest-encountered occurrences of the specified elements.
51725443 * @since 3.0.1
51735444 */
5174 public static short[] removeElements(short[] array, short... values) {
5445 public static short[] removeElements(final short[] array, final short... values) {
51755446 if (isEmpty(array) || isEmpty(values)) {
51765447 return clone(array);
51775448 }
5178 HashMap<Short, MutableInt> occurrences = new HashMap<Short, MutableInt>(values.length);
5179 for (short v : values) {
5180 Short boxed = Short.valueOf(v);
5181 MutableInt count = occurrences.get(boxed);
5449 final HashMap<Short, MutableInt> occurrences = new HashMap<Short, MutableInt>(values.length);
5450 for (final short v : values) {
5451 final Short boxed = Short.valueOf(v);
5452 final MutableInt count = occurrences.get(boxed);
51825453 if (count == null) {
51835454 occurrences.put(boxed, new MutableInt(1));
51845455 } else {
51855456 count.increment();
51865457 }
51875458 }
5188 HashSet<Integer> toRemove = new HashSet<Integer>();
5189 for (Map.Entry<Short, MutableInt> e : occurrences.entrySet()) {
5190 Short v = e.getKey();
5459 final BitSet toRemove = new BitSet();
5460 for (final Map.Entry<Short, MutableInt> e : occurrences.entrySet()) {
5461 final Short v = e.getKey();
51915462 int found = 0;
51925463 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
51935464 found = indexOf(array, v.shortValue(), found);
51945465 if (found < 0) {
51955466 break;
51965467 }
5197 toRemove.add(found++);
5468 toRemove.set(found++);
51985469 }
51995470 }
5200 return removeAll(array, extractIndices(toRemove));
5471 return (short[]) removeAll(array, toRemove);
52015472 }
52025473
52035474 /**
52295500 * (index < 0 || index >= array.length), or if the array is {@code null}.
52305501 * @since 3.0.1
52315502 */
5232 public static int[] removeAll(int[] array, int... indices) {
5503 public static int[] removeAll(final int[] array, final int... indices) {
52335504 return (int[]) removeAll((Object) array, clone(indices));
52345505 }
52355506
52605531 * earliest-encountered occurrences of the specified elements.
52615532 * @since 3.0.1
52625533 */
5263 public static int[] removeElements(int[] array, int... values) {
5534 public static int[] removeElements(final int[] array, final int... values) {
52645535 if (isEmpty(array) || isEmpty(values)) {
52655536 return clone(array);
52665537 }
5267 HashMap<Integer, MutableInt> occurrences = new HashMap<Integer, MutableInt>(values.length);
5268 for (int v : values) {
5269 Integer boxed = Integer.valueOf(v);
5270 MutableInt count = occurrences.get(boxed);
5538 final HashMap<Integer, MutableInt> occurrences = new HashMap<Integer, MutableInt>(values.length);
5539 for (final int v : values) {
5540 final Integer boxed = Integer.valueOf(v);
5541 final MutableInt count = occurrences.get(boxed);
52715542 if (count == null) {
52725543 occurrences.put(boxed, new MutableInt(1));
52735544 } else {
52745545 count.increment();
52755546 }
52765547 }
5277 HashSet<Integer> toRemove = new HashSet<Integer>();
5278 for (Map.Entry<Integer, MutableInt> e : occurrences.entrySet()) {
5279 Integer v = e.getKey();
5548 final BitSet toRemove = new BitSet();
5549 for (final Map.Entry<Integer, MutableInt> e : occurrences.entrySet()) {
5550 final Integer v = e.getKey();
52805551 int found = 0;
52815552 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
52825553 found = indexOf(array, v.intValue(), found);
52835554 if (found < 0) {
52845555 break;
52855556 }
5286 toRemove.add(found++);
5557 toRemove.set(found++);
52875558 }
52885559 }
5289 return removeAll(array, extractIndices(toRemove));
5560 return (int[]) removeAll(array, toRemove);
52905561 }
52915562
52925563 /**
53185589 * (index < 0 || index >= array.length), or if the array is {@code null}.
53195590 * @since 3.0.1
53205591 */
5321 public static char[] removeAll(char[] array, int... indices) {
5592 public static char[] removeAll(final char[] array, final int... indices) {
53225593 return (char[]) removeAll((Object) array, clone(indices));
53235594 }
53245595
53495620 * earliest-encountered occurrences of the specified elements.
53505621 * @since 3.0.1
53515622 */
5352 public static char[] removeElements(char[] array, char... values) {
5623 public static char[] removeElements(final char[] array, final char... values) {
53535624 if (isEmpty(array) || isEmpty(values)) {
53545625 return clone(array);
53555626 }
5356 HashMap<Character, MutableInt> occurrences = new HashMap<Character, MutableInt>(values.length);
5357 for (char v : values) {
5358 Character boxed = Character.valueOf(v);
5359 MutableInt count = occurrences.get(boxed);
5627 final HashMap<Character, MutableInt> occurrences = new HashMap<Character, MutableInt>(values.length);
5628 for (final char v : values) {
5629 final Character boxed = Character.valueOf(v);
5630 final MutableInt count = occurrences.get(boxed);
53605631 if (count == null) {
53615632 occurrences.put(boxed, new MutableInt(1));
53625633 } else {
53635634 count.increment();
53645635 }
53655636 }
5366 HashSet<Integer> toRemove = new HashSet<Integer>();
5367 for (Map.Entry<Character, MutableInt> e : occurrences.entrySet()) {
5368 Character v = e.getKey();
5637 final BitSet toRemove = new BitSet();
5638 for (final Map.Entry<Character, MutableInt> e : occurrences.entrySet()) {
5639 final Character v = e.getKey();
53695640 int found = 0;
53705641 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
53715642 found = indexOf(array, v.charValue(), found);
53725643 if (found < 0) {
53735644 break;
53745645 }
5375 toRemove.add(found++);
5646 toRemove.set(found++);
53765647 }
53775648 }
5378 return removeAll(array, extractIndices(toRemove));
5649 return (char[]) removeAll(array, toRemove);
53795650 }
53805651
53815652 /**
54075678 * (index < 0 || index >= array.length), or if the array is {@code null}.
54085679 * @since 3.0.1
54095680 */
5410 public static long[] removeAll(long[] array, int... indices) {
5681 public static long[] removeAll(final long[] array, final int... indices) {
54115682 return (long[]) removeAll((Object) array, clone(indices));
54125683 }
54135684
54385709 * earliest-encountered occurrences of the specified elements.
54395710 * @since 3.0.1
54405711 */
5441 public static long[] removeElements(long[] array, long... values) {
5712 public static long[] removeElements(final long[] array, final long... values) {
54425713 if (isEmpty(array) || isEmpty(values)) {
54435714 return clone(array);
54445715 }
5445 HashMap<Long, MutableInt> occurrences = new HashMap<Long, MutableInt>(values.length);
5446 for (long v : values) {
5447 Long boxed = Long.valueOf(v);
5448 MutableInt count = occurrences.get(boxed);
5716 final HashMap<Long, MutableInt> occurrences = new HashMap<Long, MutableInt>(values.length);
5717 for (final long v : values) {
5718 final Long boxed = Long.valueOf(v);
5719 final MutableInt count = occurrences.get(boxed);
54495720 if (count == null) {
54505721 occurrences.put(boxed, new MutableInt(1));
54515722 } else {
54525723 count.increment();
54535724 }
54545725 }
5455 HashSet<Integer> toRemove = new HashSet<Integer>();
5456 for (Map.Entry<Long, MutableInt> e : occurrences.entrySet()) {
5457 Long v = e.getKey();
5726 final BitSet toRemove = new BitSet();
5727 for (final Map.Entry<Long, MutableInt> e : occurrences.entrySet()) {
5728 final Long v = e.getKey();
54585729 int found = 0;
54595730 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
54605731 found = indexOf(array, v.longValue(), found);
54615732 if (found < 0) {
54625733 break;
54635734 }
5464 toRemove.add(found++);
5735 toRemove.set(found++);
54655736 }
54665737 }
5467 return removeAll(array, extractIndices(toRemove));
5738 return (long[]) removeAll(array, toRemove);
54685739 }
54695740
54705741 /**
54965767 * (index < 0 || index >= array.length), or if the array is {@code null}.
54975768 * @since 3.0.1
54985769 */
5499 public static float[] removeAll(float[] array, int... indices) {
5770 public static float[] removeAll(final float[] array, final int... indices) {
55005771 return (float[]) removeAll((Object) array, clone(indices));
55015772 }
55025773
55275798 * earliest-encountered occurrences of the specified elements.
55285799 * @since 3.0.1
55295800 */
5530 public static float[] removeElements(float[] array, float... values) {
5801 public static float[] removeElements(final float[] array, final float... values) {
55315802 if (isEmpty(array) || isEmpty(values)) {
55325803 return clone(array);
55335804 }
5534 HashMap<Float, MutableInt> occurrences = new HashMap<Float, MutableInt>(values.length);
5535 for (float v : values) {
5536 Float boxed = Float.valueOf(v);
5537 MutableInt count = occurrences.get(boxed);
5805 final HashMap<Float, MutableInt> occurrences = new HashMap<Float, MutableInt>(values.length);
5806 for (final float v : values) {
5807 final Float boxed = Float.valueOf(v);
5808 final MutableInt count = occurrences.get(boxed);
55385809 if (count == null) {
55395810 occurrences.put(boxed, new MutableInt(1));
55405811 } else {
55415812 count.increment();
55425813 }
55435814 }
5544 HashSet<Integer> toRemove = new HashSet<Integer>();
5545 for (Map.Entry<Float, MutableInt> e : occurrences.entrySet()) {
5546 Float v = e.getKey();
5815 final BitSet toRemove = new BitSet();
5816 for (final Map.Entry<Float, MutableInt> e : occurrences.entrySet()) {
5817 final Float v = e.getKey();
55475818 int found = 0;
55485819 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
55495820 found = indexOf(array, v.floatValue(), found);
55505821 if (found < 0) {
55515822 break;
55525823 }
5553 toRemove.add(found++);
5824 toRemove.set(found++);
55545825 }
55555826 }
5556 return removeAll(array, extractIndices(toRemove));
5827 return (float[]) removeAll(array, toRemove);
55575828 }
55585829
55595830 /**
55855856 * (index < 0 || index >= array.length), or if the array is {@code null}.
55865857 * @since 3.0.1
55875858 */
5588 public static double[] removeAll(double[] array, int... indices) {
5859 public static double[] removeAll(final double[] array, final int... indices) {
55895860 return (double[]) removeAll((Object) array, clone(indices));
55905861 }
55915862
56165887 * earliest-encountered occurrences of the specified elements.
56175888 * @since 3.0.1
56185889 */
5619 public static double[] removeElements(double[] array, double... values) {
5890 public static double[] removeElements(final double[] array, final double... values) {
56205891 if (isEmpty(array) || isEmpty(values)) {
56215892 return clone(array);
56225893 }
5623 HashMap<Double, MutableInt> occurrences = new HashMap<Double, MutableInt>(values.length);
5624 for (double v : values) {
5625 Double boxed = Double.valueOf(v);
5626 MutableInt count = occurrences.get(boxed);
5894 final HashMap<Double, MutableInt> occurrences = new HashMap<Double, MutableInt>(values.length);
5895 for (final double v : values) {
5896 final Double boxed = Double.valueOf(v);
5897 final MutableInt count = occurrences.get(boxed);
56275898 if (count == null) {
56285899 occurrences.put(boxed, new MutableInt(1));
56295900 } else {
56305901 count.increment();
56315902 }
56325903 }
5633 HashSet<Integer> toRemove = new HashSet<Integer>();
5634 for (Map.Entry<Double, MutableInt> e : occurrences.entrySet()) {
5635 Double v = e.getKey();
5904 final BitSet toRemove = new BitSet();
5905 for (final Map.Entry<Double, MutableInt> e : occurrences.entrySet()) {
5906 final Double v = e.getKey();
56365907 int found = 0;
56375908 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
56385909 found = indexOf(array, v.doubleValue(), found);
56395910 if (found < 0) {
56405911 break;
56415912 }
5642 toRemove.add(found++);
5913 toRemove.set(found++);
56435914 }
56445915 }
5645 return removeAll(array, extractIndices(toRemove));
5916 return (double[]) removeAll(array, toRemove);
56465917 }
56475918
56485919 /**
56705941 * (index < 0 || index >= array.length), or if the array is {@code null}.
56715942 * @since 3.0.1
56725943 */
5673 public static boolean[] removeAll(boolean[] array, int... indices) {
5944 public static boolean[] removeAll(final boolean[] array, final int... indices) {
56745945 return (boolean[]) removeAll((Object) array, clone(indices));
56755946 }
56765947
57015972 * earliest-encountered occurrences of the specified elements.
57025973 * @since 3.0.1
57035974 */
5704 public static boolean[] removeElements(boolean[] array, boolean... values) {
5975 public static boolean[] removeElements(final boolean[] array, final boolean... values) {
57055976 if (isEmpty(array) || isEmpty(values)) {
57065977 return clone(array);
57075978 }
5708 HashMap<Boolean, MutableInt> occurrences = new HashMap<Boolean, MutableInt>(values.length);
5709 for (boolean v : values) {
5710 Boolean boxed = Boolean.valueOf(v);
5711 MutableInt count = occurrences.get(boxed);
5979 final HashMap<Boolean, MutableInt> occurrences = new HashMap<Boolean, MutableInt>(2); // only two possible values here
5980 for (final boolean v : values) {
5981 final Boolean boxed = Boolean.valueOf(v);
5982 final MutableInt count = occurrences.get(boxed);
57125983 if (count == null) {
57135984 occurrences.put(boxed, new MutableInt(1));
57145985 } else {
57155986 count.increment();
57165987 }
57175988 }
5718 HashSet<Integer> toRemove = new HashSet<Integer>();
5719 for (Map.Entry<Boolean, MutableInt> e : occurrences.entrySet()) {
5720 Boolean v = e.getKey();
5989 final BitSet toRemove = new BitSet();
5990 for (final Map.Entry<Boolean, MutableInt> e : occurrences.entrySet()) {
5991 final Boolean v = e.getKey();
57215992 int found = 0;
57225993 for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
57235994 found = indexOf(array, v.booleanValue(), found);
57245995 if (found < 0) {
57255996 break;
57265997 }
5727 toRemove.add(found++);
5998 toRemove.set(found++);
57285999 }
57296000 }
5730 return removeAll(array, extractIndices(toRemove));
6001 return (boolean[]) removeAll(array, toRemove);
57316002 }
57326003
57336004 /**
57376008 * @return new array of same type minus elements specified by unique values of {@code indices}
57386009 * @since 3.0.1
57396010 */
5740 private static Object removeAll(Object array, int... indices) {
5741 int length = getLength(array);
5742 int diff = 0;
6011 // package protected for access by unit tests
6012 static Object removeAll(final Object array, final int... indices) {
6013 final int length = getLength(array);
6014 int diff = 0; // number of distinct indexes, i.e. number of entries that will be removed
57436015
57446016 if (isNotEmpty(indices)) {
57456017 Arrays.sort(indices);
57476019 int i = indices.length;
57486020 int prevIndex = length;
57496021 while (--i >= 0) {
5750 int index = indices[i];
6022 final int index = indices[i];
57516023 if (index < 0 || index >= length) {
57526024 throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
57536025 }
57586030 prevIndex = index;
57596031 }
57606032 }
5761 Object result = Array.newInstance(array.getClass().getComponentType(), length - diff);
6033 final Object result = Array.newInstance(array.getClass().getComponentType(), length - diff);
57626034 if (diff < length) {
5763 int end = length;
5764 int dest = length - diff;
6035 int end = length; // index just after last copy
6036 int dest = length - diff; // number of entries so far not copied
57656037 for (int i = indices.length - 1; i >= 0; i--) {
5766 int index = indices[i];
5767 if (end - index > 1) {
5768 int cp = end - index - 1;
6038 final int index = indices[i];
6039 if (end - index > 1) { // same as (cp > 0)
6040 final int cp = end - index - 1;
57696041 dest -= cp;
57706042 System.arraycopy(array, index + 1, result, dest, cp);
6043 // Afer this copy, we still have room for dest items.
57716044 }
57726045 end = index;
57736046 }
57796052 }
57806053
57816054 /**
5782 * Extract a set of Integer indices into an int[].
5783 * @param coll {@code HashSet} of {@code Integer}
5784 * @return int[]
5785 * @since 3.0.1
5786 */
5787 private static int[] extractIndices(HashSet<Integer> coll) {
5788 int[] result = new int[coll.size()];
5789 int i = 0;
5790 for (Integer index : coll) {
5791 result[i++] = index.intValue();
6055 * Removes multiple array elements specified by indices.
6056 *
6057 * @param array source
6058 * @param indices to remove
6059 * @return new array of same type minus elements specified by the set bits in {@code indices}
6060 * @since 3.2
6061 */
6062 // package protected for access by unit tests
6063 static Object removeAll(final Object array, final BitSet indices) {
6064 final int srcLength = ArrayUtils.getLength(array);
6065 // No need to check maxIndex here, because method only currently called from removeElements()
6066 // which guarantee to generate on;y valid bit entries.
6067 // final int maxIndex = indices.length();
6068 // if (maxIndex > srcLength) {
6069 // throw new IndexOutOfBoundsException("Index: " + (maxIndex-1) + ", Length: " + srcLength);
6070 // }
6071 final int removals = indices.cardinality(); // true bits are items to remove
6072 final Object result = Array.newInstance(array.getClass().getComponentType(), srcLength - removals);
6073 int srcIndex=0;
6074 int destIndex=0;
6075 int count;
6076 int set;
6077 while((set = indices.nextSetBit(srcIndex)) != -1){
6078 count = set - srcIndex;
6079 if (count > 0) {
6080 System.arraycopy(array, srcIndex, result, destIndex, count);
6081 destIndex += count;
6082 }
6083 srcIndex = indices.nextClearBit(set);
6084 }
6085 count = srcLength - srcIndex;
6086 if (count > 0) {
6087 System.arraycopy(array, srcIndex, result, destIndex, count);
57926088 }
57936089 return result;
57946090 }
1919 * <p>Operations on bit-mapped fields.</p>
2020 *
2121 * @since 2.0
22 * @version $Id: BitField.java 1088899 2011-04-05 05:31:27Z bayard $
22 * @version $Id: BitField.java 1436768 2013-01-22 07:07:42Z ggregory $
2323 */
2424 public class BitField {
2525
3333 * BitField. Bits that are set in this mask are the bits
3434 * that this BitField operates on
3535 */
36 public BitField(int mask) {
36 public BitField(final int mask) {
3737 _mask = mask;
3838 int count = 0;
3939 int bit_pattern = mask;
6161 * in
6262 * @return the selected bits, shifted right appropriately
6363 */
64 public int getValue(int holder) {
64 public int getValue(final int holder) {
6565 return getRawValue(holder) >> _shift_count;
6666 }
6767
7979 * interested in
8080 * @return the selected bits, shifted right appropriately
8181 */
82 public short getShortValue(short holder) {
82 public short getShortValue(final short holder) {
8383 return (short) getValue(holder);
8484 }
8585
9090 * interested in
9191 * @return the selected bits
9292 */
93 public int getRawValue(int holder) {
93 public int getRawValue(final int holder) {
9494 return holder & _mask;
9595 }
9696
101101 * interested in
102102 * @return the selected bits
103103 */
104 public short getShortRawValue(short holder) {
104 public short getShortRawValue(final short holder) {
105105 return (short) getRawValue(holder);
106106 }
107107
118118 * @return {@code true} if any of the bits are set,
119119 * else {@code false}
120120 */
121 public boolean isSet(int holder) {
121 public boolean isSet(final int holder) {
122122 return (holder & _mask) != 0;
123123 }
124124
134134 * @return {@code true} if all of the bits are set,
135135 * else {@code false}
136136 */
137 public boolean isAllSet(int holder) {
137 public boolean isAllSet(final int holder) {
138138 return (holder & _mask) == _mask;
139139 }
140140
148148 * @return the value of holder with the bits from the value
149149 * parameter replacing the old bits
150150 */
151 public int setValue(int holder, int value) {
151 public int setValue(final int holder, final int value) {
152152 return (holder & ~_mask) | ((value << _shift_count) & _mask);
153153 }
154154
162162 * @return the value of holder with the bits from the value
163163 * parameter replacing the old bits
164164 */
165 public short setShortValue(short holder, short value) {
165 public short setShortValue(final short holder, final short value) {
166166 return (short) setValue(holder, value);
167167 }
168168
174174 * @return the value of holder with the specified bits cleared
175175 * (set to {@code 0})
176176 */
177 public int clear(int holder) {
177 public int clear(final int holder) {
178178 return holder & ~_mask;
179179 }
180180
186186 * @return the value of holder with the specified bits cleared
187187 * (set to {@code 0})
188188 */
189 public short clearShort(short holder) {
189 public short clearShort(final short holder) {
190190 return (short) clear(holder);
191191 }
192192
199199 * @return the value of holder with the specified bits cleared
200200 * (set to {@code 0})
201201 */
202 public byte clearByte(byte holder) {
202 public byte clearByte(final byte holder) {
203203 return (byte) clear(holder);
204204 }
205205
211211 * @return the value of holder with the specified bits set
212212 * to {@code 1}
213213 */
214 public int set(int holder) {
214 public int set(final int holder) {
215215 return holder | _mask;
216216 }
217217
223223 * @return the value of holder with the specified bits set
224224 * to {@code 1}
225225 */
226 public short setShort(short holder) {
226 public short setShort(final short holder) {
227227 return (short) set(holder);
228228 }
229229
236236 * @return the value of holder with the specified bits set
237237 * to {@code 1}
238238 */
239 public byte setByte(byte holder) {
239 public byte setByte(final byte holder) {
240240 return (byte) set(holder);
241241 }
242242
249249 * @return the value of holder with the specified bits set or
250250 * cleared
251251 */
252 public int setBoolean(int holder, boolean flag) {
252 public int setBoolean(final int holder, final boolean flag) {
253253 return flag ? set(holder) : clear(holder);
254254 }
255255
262262 * @return the value of holder with the specified bits set or
263263 * cleared
264264 */
265 public short setShortBoolean(short holder, boolean flag) {
265 public short setShortBoolean(final short holder, final boolean flag) {
266266 return flag ? setShort(holder) : clearShort(holder);
267267 }
268268
275275 * @return the value of holder with the specified bits set or
276276 * cleared
277277 */
278 public byte setByteBoolean(byte holder, boolean flag) {
278 public byte setByteBoolean(final byte holder, final boolean flag) {
279279 return flag ? setByte(holder) : clearByte(holder);
280280 }
281281
2626 *
2727 * <p>#ThreadSafe#</p>
2828 * @since 2.0
29 * @version $Id: BooleanUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
29 * @version $Id: BooleanUtils.java 1534738 2013-10-22 19:23:21Z britter $
3030 */
3131 public class BooleanUtils {
3232
5959 * @param bool the Boolean to negate, may be null
6060 * @return the negated Boolean, or {@code null} if {@code null} input
6161 */
62 public static Boolean negate(Boolean bool) {
62 public static Boolean negate(final Boolean bool) {
6363 if (bool == null) {
6464 return null;
6565 }
8282 * @return {@code true} only if the input is non-null and true
8383 * @since 2.1
8484 */
85 public static boolean isTrue(Boolean bool) {
85 public static boolean isTrue(final Boolean bool) {
8686 return Boolean.TRUE.equals(bool);
8787 }
8888
100100 * @return {@code true} if the input is null or false
101101 * @since 2.3
102102 */
103 public static boolean isNotTrue(Boolean bool) {
103 public static boolean isNotTrue(final Boolean bool) {
104104 return !isTrue(bool);
105105 }
106106
118118 * @return {@code true} only if the input is non-null and false
119119 * @since 2.1
120120 */
121 public static boolean isFalse(Boolean bool) {
121 public static boolean isFalse(final Boolean bool) {
122122 return Boolean.FALSE.equals(bool);
123123 }
124124
136136 * @return {@code true} if the input is null or true
137137 * @since 2.3
138138 */
139 public static boolean isNotFalse(Boolean bool) {
139 public static boolean isNotFalse(final Boolean bool) {
140140 return !isFalse(bool);
141141 }
142142
154154 * @param bool the boolean to convert
155155 * @return {@code true} or {@code false}, {@code null} returns {@code false}
156156 */
157 public static boolean toBoolean(Boolean bool) {
157 public static boolean toBoolean(final Boolean bool) {
158158 return bool != null && bool.booleanValue();
159159 }
160160
171171 * @param valueIfNull the boolean value to return if {@code null}
172172 * @return {@code true} or {@code false}
173173 */
174 public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) {
174 public static boolean toBooleanDefaultIfNull(final Boolean bool, final boolean valueIfNull) {
175175 if (bool == null) {
176176 return valueIfNull;
177177 }
194194 * @return {@code true} if non-zero, {@code false}
195195 * if zero
196196 */
197 public static boolean toBoolean(int value) {
197 public static boolean toBoolean(final int value) {
198198 return value != 0;
199199 }
200200
212212 * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,
213213 * {@code null} if {@code null}
214214 */
215 public static Boolean toBooleanObject(int value) {
215 public static Boolean toBooleanObject(final int value) {
216216 return value == 0 ? Boolean.FALSE : Boolean.TRUE;
217217 }
218218
234234 * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,
235235 * {@code null} if {@code null} input
236236 */
237 public static Boolean toBooleanObject(Integer value) {
237 public static Boolean toBooleanObject(final Integer value) {
238238 if (value == null) {
239239 return null;
240240 }
257257 * @return {@code true} or {@code false}
258258 * @throws IllegalArgumentException if no match
259259 */
260 public static boolean toBoolean(int value, int trueValue, int falseValue) {
260 public static boolean toBoolean(final int value, final int trueValue, final int falseValue) {
261261 if (value == trueValue) {
262262 return true;
263263 }
285285 * @return {@code true} or {@code false}
286286 * @throws IllegalArgumentException if no match
287287 */
288 public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) {
288 public static boolean toBoolean(final Integer value, final Integer trueValue, final Integer falseValue) {
289289 if (value == null) {
290290 if (trueValue == null) {
291291 return true;
320320 * @return Boolean.TRUE, Boolean.FALSE, or {@code null}
321321 * @throws IllegalArgumentException if no match
322322 */
323 public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) {
323 public static Boolean toBooleanObject(final int value, final int trueValue, final int falseValue, final int nullValue) {
324324 if (value == trueValue) {
325325 return Boolean.TRUE;
326326 }
352352 * @return Boolean.TRUE, Boolean.FALSE, or {@code null}
353353 * @throws IllegalArgumentException if no match
354354 */
355 public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) {
355 public static Boolean toBooleanObject(final Integer value, final Integer trueValue, final Integer falseValue, final Integer nullValue) {
356356 if (value == null) {
357357 if (trueValue == null) {
358358 return Boolean.TRUE;
388388 * @param bool the boolean to convert
389389 * @return one if {@code true}, zero if {@code false}
390390 */
391 public static int toInteger(boolean bool) {
391 public static int toInteger(final boolean bool) {
392392 return bool ? 1 : 0;
393393 }
394394
404404 * @param bool the boolean to convert
405405 * @return one if {@code true}, zero if {@code false}
406406 */
407 public static Integer toIntegerObject(boolean bool) {
407 public static Integer toIntegerObject(final boolean bool) {
408408 return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
409409 }
410410
422422 * @param bool the Boolean to convert
423423 * @return one if Boolean.TRUE, zero if Boolean.FALSE, {@code null} if {@code null}
424424 */
425 public static Integer toIntegerObject(Boolean bool) {
425 public static Integer toIntegerObject(final Boolean bool) {
426426 if (bool == null) {
427427 return null;
428428 }
442442 * @param falseValue the value to return if {@code false}
443443 * @return the appropriate value
444444 */
445 public static int toInteger(boolean bool, int trueValue, int falseValue) {
445 public static int toInteger(final boolean bool, final int trueValue, final int falseValue) {
446446 return bool ? trueValue : falseValue;
447447 }
448448
461461 * @param nullValue the value to return if {@code null}
462462 * @return the appropriate value
463463 */
464 public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) {
464 public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) {
465465 if (bool == null) {
466466 return nullValue;
467467 }
481481 * @param falseValue the value to return if {@code false}, may be {@code null}
482482 * @return the appropriate value
483483 */
484 public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) {
484 public static Integer toIntegerObject(final boolean bool, final Integer trueValue, final Integer falseValue) {
485485 return bool ? trueValue : falseValue;
486486 }
487487
500500 * @param nullValue the value to return if {@code null}, may be {@code null}
501501 * @return the appropriate value
502502 */
503 public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) {
503 public static Integer toIntegerObject(final Boolean bool, final Integer trueValue, final Integer falseValue, final Integer nullValue) {
504504 if (bool == null) {
505505 return nullValue;
506506 }
512512 /**
513513 * <p>Converts a String to a Boolean.</p>
514514 *
515 * <p>{@code 'true'}, {@code 'on'} or {@code 'yes'}
515 * <p>{@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'}
516516 * (case insensitive) will return {@code true}.
517 * {@code 'false'}, {@code 'off'} or {@code 'no'}
517 * {@code 'false'}, {@code 'off'}, {@code 'n'}, {@code 'f'} or {@code 'no'}
518518 * (case insensitive) will return {@code false}.
519519 * Otherwise, {@code null} is returned.</p>
520520 *
521521 * <p>NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean. </p>
522522 *
523523 * <pre>
524 * // N.B. case is not significant
524525 * BooleanUtils.toBooleanObject(null) = null
525526 * BooleanUtils.toBooleanObject("true") = Boolean.TRUE
527 * BooleanUtils.toBooleanObject("T") = Boolean.TRUE // i.e. T[RUE]
526528 * BooleanUtils.toBooleanObject("false") = Boolean.FALSE
529 * BooleanUtils.toBooleanObject("f") = Boolean.FALSE // i.e. f[alse]
530 * BooleanUtils.toBooleanObject("No") = Boolean.FALSE
531 * BooleanUtils.toBooleanObject("n") = Boolean.FALSE // i.e. n[o]
527532 * BooleanUtils.toBooleanObject("on") = Boolean.TRUE
528533 * BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
529534 * BooleanUtils.toBooleanObject("off") = Boolean.FALSE
530535 * BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
536 * BooleanUtils.toBooleanObject("yes") = Boolean.TRUE
537 * BooleanUtils.toBooleanObject("Y") = Boolean.TRUE // i.e. Y[ES]
531538 * BooleanUtils.toBooleanObject("blue") = null
532539 * </pre>
533540 *
534 * @param str the String to check
541 * @param str the String to check; upper and lower case are treated as the same
535542 * @return the Boolean value of the string, {@code null} if no match or {@code null} input
536543 */
537 public static Boolean toBooleanObject(String str) {
544 public static Boolean toBooleanObject(final String str) {
538545 // Previously used equalsIgnoreCase, which was fast for interned 'true'.
539546 // Non interned 'true' matched 15 times slower.
540547 //
549556 }
550557 switch (str.length()) {
551558 case 1: {
552 char ch0 = str.charAt(0);
559 final char ch0 = str.charAt(0);
553560 if (ch0 == 'y' || ch0 == 'Y' ||
554561 ch0 == 't' || ch0 == 'T') {
555562 return Boolean.TRUE;
561568 break;
562569 }
563570 case 2: {
564 char ch0 = str.charAt(0);
565 char ch1 = str.charAt(1);
571 final char ch0 = str.charAt(0);
572 final char ch1 = str.charAt(1);
566573 if ((ch0 == 'o' || ch0 == 'O') &&
567574 (ch1 == 'n' || ch1 == 'N') ) {
568575 return Boolean.TRUE;
574581 break;
575582 }
576583 case 3: {
577 char ch0 = str.charAt(0);
578 char ch1 = str.charAt(1);
579 char ch2 = str.charAt(2);
584 final char ch0 = str.charAt(0);
585 final char ch1 = str.charAt(1);
586 final char ch2 = str.charAt(2);
580587 if ((ch0 == 'y' || ch0 == 'Y') &&
581588 (ch1 == 'e' || ch1 == 'E') &&
582589 (ch2 == 's' || ch2 == 'S') ) {
590597 break;
591598 }
592599 case 4: {
593 char ch0 = str.charAt(0);
594 char ch1 = str.charAt(1);
595 char ch2 = str.charAt(2);
596 char ch3 = str.charAt(3);
600 final char ch0 = str.charAt(0);
601 final char ch1 = str.charAt(1);
602 final char ch2 = str.charAt(2);
603 final char ch3 = str.charAt(3);
597604 if ((ch0 == 't' || ch0 == 'T') &&
598605 (ch1 == 'r' || ch1 == 'R') &&
599606 (ch2 == 'u' || ch2 == 'U') &&
603610 break;
604611 }
605612 case 5: {
606 char ch0 = str.charAt(0);
607 char ch1 = str.charAt(1);
608 char ch2 = str.charAt(2);
609 char ch3 = str.charAt(3);
610 char ch4 = str.charAt(4);
613 final char ch0 = str.charAt(0);
614 final char ch1 = str.charAt(1);
615 final char ch2 = str.charAt(2);
616 final char ch3 = str.charAt(3);
617 final char ch4 = str.charAt(4);
611618 if ((ch0 == 'f' || ch0 == 'F') &&
612619 (ch1 == 'a' || ch1 == 'A') &&
613620 (ch2 == 'l' || ch2 == 'L') &&
641648 * or if {@code null} input and {@code nullString} is {@code null}
642649 * @throws IllegalArgumentException if the String doesn't match
643650 */
644 public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) {
651 public static Boolean toBooleanObject(final String str, final String trueString, final String falseString, final String nullString) {
645652 if (str == null) {
646653 if (trueString == null) {
647654 return Boolean.TRUE;
668675 /**
669676 * <p>Converts a String to a boolean (optimised for performance).</p>
670677 *
671 * <p>{@code 'true'}, {@code 'on'} or {@code 'yes'}
678 * <p>{@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'}
672679 * (case insensitive) will return {@code true}. Otherwise,
673680 * {@code false} is returned.</p>
674681 *
675682 * <p>This method performs 4 times faster (JDK1.4) than
676683 * {@code Boolean.valueOf(String)}. However, this method accepts
677 * 'on' and 'yes' as true values.
684 * 'on' and 'yes', 't', 'y' as true values.
678685 *
679686 * <pre>
680687 * BooleanUtils.toBoolean(null) = false
685692 * BooleanUtils.toBoolean("yes") = true
686693 * BooleanUtils.toBoolean("false") = false
687694 * BooleanUtils.toBoolean("x gti") = false
695 * BooleanUtils.toBooleanObject("y") = true
696 * BooleanUtils.toBooleanObject("n") = false
697 * BooleanUtils.toBooleanObject("t") = true
698 * BooleanUtils.toBooleanObject("f") = false
688699 * </pre>
689700 *
690701 * @param str the String to check
691702 * @return the boolean value of the string, {@code false} if no match or the String is null
692703 */
693 public static boolean toBoolean(String str) {
704 public static boolean toBoolean(final String str) {
694705 return toBooleanObject(str) == Boolean.TRUE;
695706 }
696707
708719 * @return the boolean value of the string
709720 * @throws IllegalArgumentException if the String doesn't match
710721 */
711 public static boolean toBoolean(String str, String trueString, String falseString) {
722 public static boolean toBoolean(final String str, final String trueString, final String falseString) {
712723 if (str == trueString) {
713724 return true;
714725 } else if (str == falseString) {
739750 * @param bool the Boolean to check
740751 * @return {@code 'true'}, {@code 'false'}, or {@code null}
741752 */
742 public static String toStringTrueFalse(Boolean bool) {
753 public static String toStringTrueFalse(final Boolean bool) {
743754 return toString(bool, "true", "false", null);
744755 }
745756
756767 * @param bool the Boolean to check
757768 * @return {@code 'on'}, {@code 'off'}, or {@code null}
758769 */
759 public static String toStringOnOff(Boolean bool) {
770 public static String toStringOnOff(final Boolean bool) {
760771 return toString(bool, "on", "off", null);
761772 }
762773
773784 * @param bool the Boolean to check
774785 * @return {@code 'yes'}, {@code 'no'}, or {@code null}
775786 */
776 public static String toStringYesNo(Boolean bool) {
787 public static String toStringYesNo(final Boolean bool) {
777788 return toString(bool, "yes", "no", null);
778789 }
779790
792803 * @param nullString the String to return if {@code null}, may be {@code null}
793804 * @return one of the three input Strings
794805 */
795 public static String toString(Boolean bool, String trueString, String falseString, String nullString) {
806 public static String toString(final Boolean bool, final String trueString, final String falseString, final String nullString) {
796807 if (bool == null) {
797808 return nullString;
798809 }
813824 * @param bool the Boolean to check
814825 * @return {@code 'true'}, {@code 'false'}, or {@code null}
815826 */
816 public static String toStringTrueFalse(boolean bool) {
827 public static String toStringTrueFalse(final boolean bool) {
817828 return toString(bool, "true", "false");
818829 }
819830
829840 * @param bool the Boolean to check
830841 * @return {@code 'on'}, {@code 'off'}, or {@code null}
831842 */
832 public static String toStringOnOff(boolean bool) {
843 public static String toStringOnOff(final boolean bool) {
833844 return toString(bool, "on", "off");
834845 }
835846
845856 * @param bool the Boolean to check
846857 * @return {@code 'yes'}, {@code 'no'}, or {@code null}
847858 */
848 public static String toStringYesNo(boolean bool) {
859 public static String toStringYesNo(final boolean bool) {
849860 return toString(bool, "yes", "no");
850861 }
851862
862873 * @param falseString the String to return if {@code false}, may be {@code null}
863874 * @return one of the two input Strings
864875 */
865 public static String toString(boolean bool, String trueString, String falseString) {
876 public static String toString(final boolean bool, final String trueString, final String falseString) {
866877 return bool ? trueString : falseString;
867878 }
868879
885896 * @throws IllegalArgumentException if {@code array} is empty.
886897 * @since 3.0.1
887898 */
888 public static boolean and(boolean... array) {
899 public static boolean and(final boolean... array) {
889900 // Validates input
890901 if (array == null) {
891902 throw new IllegalArgumentException("The Array must not be null");
893904 if (array.length == 0) {
894905 throw new IllegalArgumentException("Array is empty");
895906 }
896 for (boolean element : array) {
907 for (final boolean element : array) {
897908 if (!element) {
898909 return false;
899910 }
920931 * @throws IllegalArgumentException if {@code array} contains a {@code null}
921932 * @since 3.0.1
922933 */
923 public static Boolean and(Boolean... array) {
934 public static Boolean and(final Boolean... array) {
924935 if (array == null) {
925936 throw new IllegalArgumentException("The Array must not be null");
926937 }
928939 throw new IllegalArgumentException("Array is empty");
929940 }
930941 try {
931 boolean[] primitive = ArrayUtils.toPrimitive(array);
942 final boolean[] primitive = ArrayUtils.toPrimitive(array);
932943 return and(primitive) ? Boolean.TRUE : Boolean.FALSE;
933 } catch (NullPointerException ex) {
944 } catch (final NullPointerException ex) {
934945 throw new IllegalArgumentException("The array must not contain any null elements");
935946 }
936947 }
953964 * @throws IllegalArgumentException if {@code array} is empty.
954965 * @since 3.0.1
955966 */
956 public static boolean or(boolean... array) {
967 public static boolean or(final boolean... array) {
957968 // Validates input
958969 if (array == null) {
959970 throw new IllegalArgumentException("The Array must not be null");
961972 if (array.length == 0) {
962973 throw new IllegalArgumentException("Array is empty");
963974 }
964 for (boolean element : array) {
975 for (final boolean element : array) {
965976 if (element) {
966977 return true;
967978 }
9891000 * @throws IllegalArgumentException if {@code array} contains a {@code null}
9901001 * @since 3.0.1
9911002 */
992 public static Boolean or(Boolean... array) {
1003 public static Boolean or(final Boolean... array) {
9931004 if (array == null) {
9941005 throw new IllegalArgumentException("The Array must not be null");
9951006 }
9971008 throw new IllegalArgumentException("Array is empty");
9981009 }
9991010 try {
1000 boolean[] primitive = ArrayUtils.toPrimitive(array);
1011 final boolean[] primitive = ArrayUtils.toPrimitive(array);
10011012 return or(primitive) ? Boolean.TRUE : Boolean.FALSE;
1002 } catch (NullPointerException ex) {
1013 } catch (final NullPointerException ex) {
10031014 throw new IllegalArgumentException("The array must not contain any null elements");
10041015 }
10051016 }
10211032 * @throws IllegalArgumentException if {@code array} is {@code null}
10221033 * @throws IllegalArgumentException if {@code array} is empty.
10231034 */
1024 public static boolean xor(boolean... array) {
1035 public static boolean xor(final boolean... array) {
10251036 // Validates input
10261037 if (array == null) {
10271038 throw new IllegalArgumentException("The Array must not be null");
10301041 throw new IllegalArgumentException("Array is empty");
10311042 }
10321043
1033 // Loops through array, comparing each item
1034 int trueCount = 0;
1035 for (boolean element : array) {
1036 // If item is true, and trueCount is < 1, increments count
1037 // Else, xor fails
1038 if (element) {
1039 if (trueCount < 1) {
1040 trueCount++;
1041 } else {
1042 return false;
1043 }
1044 }
1045 }
1046
1047 // Returns true if there was exactly 1 true item
1048 return trueCount == 1;
1044 // false if the neutral element of the xor operator
1045 boolean result = false;
1046 for (final boolean element : array) {
1047 result ^= element;
1048 }
1049
1050 return result;
10491051 }
10501052
10511053 /**
10631065 * @throws IllegalArgumentException if {@code array} is empty.
10641066 * @throws IllegalArgumentException if {@code array} contains a {@code null}
10651067 */
1066 public static Boolean xor(Boolean... array) {
1068 public static Boolean xor(final Boolean... array) {
10671069 if (array == null) {
10681070 throw new IllegalArgumentException("The Array must not be null");
10691071 }
10711073 throw new IllegalArgumentException("Array is empty");
10721074 }
10731075 try {
1074 boolean[] primitive = ArrayUtils.toPrimitive(array);
1076 final boolean[] primitive = ArrayUtils.toPrimitive(array);
10751077 return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
1076 } catch (NullPointerException ex) {
1078 } catch (final NullPointerException ex) {
10771079 throw new IllegalArgumentException("The array must not contain any null elements");
10781080 }
10791081 }
2222 /**
2323 * <p>Character encoding names required of every implementation of the Java platform.</p>
2424 *
25 * <p>According to <a href="http://java.sun.com/j2se/1.3/docs/api/java/lang/package-summary.html#charenc">JRE character
25 * <p>According to <a href="http://docs.oracle.com/javase/1.3/docs/api/java/lang/package-summary.html#charenc">JRE character
2626 * encoding names</a>:</p>
2727 *
2828 * <p><cite>Every implementation of the Java platform is required to support the following character encodings.
3131 *
3232 * @see <a href="http://download.oracle.com/javase/1.3/docs/guide/intl/encoding.doc.html">JRE character encoding names</a>
3333 * @since 2.1
34 * @version $Id: CharEncoding.java 1088899 2011-04-05 05:31:27Z bayard $
34 * @version $Id: CharEncoding.java 1459653 2013-03-22 07:37:03Z bayard $
3535 */
3636 public class CharEncoding {
3737
9090 * @param name the name of the requested charset; may be either a canonical name or an alias, null returns false
9191 * @return {@code true} if the charset is available in the current Java virtual machine
9292 */
93 public static boolean isSupported(String name) {
93 public static boolean isSupported(final String name) {
9494 if (name == null) {
9595 return false;
9696 }
9797 try {
9898 return Charset.isSupported(name);
99 } catch (IllegalCharsetNameException ex) {
99 } catch (final IllegalCharsetNameException ex) {
100100 return false;
101101 }
102102 }
2626 *
2727 * <p>#ThreadSafe#</p>
2828 * @since 1.0
29 * @version $Id: CharRange.java 1090427 2011-04-08 20:17:10Z bayard $
29 * @version $Id: CharRange.java 1436770 2013-01-22 07:09:45Z ggregory $
3030 */
3131 // TODO: This is no longer public and will be removed later as CharSet is moved
3232 // to depend on Range.
6363 * @param end last character, inclusive, in this range
6464 * @param negated true to express everything except the range
6565 */
66 private CharRange(char start, char end, boolean negated) {
66 private CharRange(char start, char end, final boolean negated) {
6767 super();
6868 if (start > end) {
69 char temp = start;
69 final char temp = start;
7070 start = end;
7171 end = temp;
7272 }
8484 * @see CharRange#CharRange(char, char, boolean)
8585 * @since 2.5
8686 */
87 public static CharRange is(char ch) {
87 public static CharRange is(final char ch) {
8888 return new CharRange(ch, ch, false);
8989 }
9090
9696 * @see CharRange#CharRange(char, char, boolean)
9797 * @since 2.5
9898 */
99 public static CharRange isNot(char ch) {
99 public static CharRange isNot(final char ch) {
100100 return new CharRange(ch, ch, true);
101101 }
102102
109109 * @see CharRange#CharRange(char, char, boolean)
110110 * @since 2.5
111111 */
112 public static CharRange isIn(char start, char end) {
112 public static CharRange isIn(final char start, final char end) {
113113 return new CharRange(start, end, false);
114114 }
115115
122122 * @see CharRange#CharRange(char, char, boolean)
123123 * @since 2.5
124124 */
125 public static CharRange isNotIn(char start, char end) {
125 public static CharRange isNotIn(final char start, final char end) {
126126 return new CharRange(start, end, true);
127127 }
128128
166166 * @param ch the character to check
167167 * @return {@code true} if this range contains the input character
168168 */
169 public boolean contains(char ch) {
169 public boolean contains(final char ch) {
170170 return (ch >= start && ch <= end) != negated;
171171 }
172172
178178 * @return {@code true} if this range entirely contains the input range
179179 * @throws IllegalArgumentException if {@code null} input
180180 */
181 public boolean contains(CharRange range) {
181 public boolean contains(final CharRange range) {
182182 if (range == null) {
183183 throw new IllegalArgumentException("The Range must not be null");
184184 }
204204 * @return true if equal
205205 */
206206 @Override
207 public boolean equals(Object obj) {
207 public boolean equals(final Object obj) {
208208 if (obj == this) {
209209 return true;
210210 }
211211 if (obj instanceof CharRange == false) {
212212 return false;
213213 }
214 CharRange other = (CharRange) obj;
214 final CharRange other = (CharRange) obj;
215215 return start == other.start && end == other.end && negated == other.negated;
216216 }
217217
233233 @Override
234234 public String toString() {
235235 if (iToString == null) {
236 StringBuilder buf = new StringBuilder(4);
236 final StringBuilder buf = new StringBuilder(4);
237237 if (isNegated()) {
238238 buf.append('^');
239239 }
252252 /**
253253 * <p>Returns an iterator which can be used to walk through the characters described by this range.</p>
254254 *
255 * <p>#NotThreadSafe# the iterator is not threadsafe</p>
255 * <p>#NotThreadSafe# the iterator is not thread-safe</p>
256256 * @return an iterator to the chars represented by this range
257257 * @since 2.5
258258 */
259 @Override
259260 public Iterator<Character> iterator() {
260261 return new CharacterIterator(this);
261262 }
276277 *
277278 * @param r The character range
278279 */
279 private CharacterIterator(CharRange r) {
280 private CharacterIterator(final CharRange r) {
280281 range = r;
281282 hasNext = true;
282283
324325 *
325326 * @return {@code true} if the iterator has yet to reach the character date
326327 */
328 @Override
327329 public boolean hasNext() {
328330 return hasNext;
329331 }
333335 *
334336 * @return {@code Character} for the next character
335337 */
338 @Override
336339 public Character next() {
337340 if (hasNext == false) {
338341 throw new NoSuchElementException();
339342 }
340 char cur = current;
343 final char cur = current;
341344 prepareNext();
342345 return Character.valueOf(cur);
343346 }
348351 * @throws UnsupportedOperationException
349352 * @see java.util.Iterator#remove()
350353 */
354 @Override
351355 public void remove() {
352356 throw new UnsupportedOperationException();
353357 }
2121 *
2222 * @see java.lang.CharSequence
2323 * @since 3.0
24 * @version $Id: CharSequenceUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
24 * @version $Id: CharSequenceUtils.java 1469220 2013-04-18 08:15:47Z bayard $
2525 */
2626 public class CharSequenceUtils {
2727
5151 * @throws IndexOutOfBoundsException if {@code start} is negative or if
5252 * {@code start} is greater than {@code length()}
5353 */
54 public static CharSequence subSequence(CharSequence cs, int start) {
54 public static CharSequence subSequence(final CharSequence cs, final int start) {
5555 return cs == null ? null : cs.subSequence(start, cs.length());
5656 }
5757
6565 * @param start the start index, negative starts at the string start
6666 * @return the index where the search char was found, -1 if not found
6767 */
68 static int indexOf(CharSequence cs, int searchChar, int start) {
68 static int indexOf(final CharSequence cs, final int searchChar, int start) {
6969 if (cs instanceof String) {
7070 return ((String) cs).indexOf(searchChar, start);
7171 } else {
72 int sz = cs.length();
72 final int sz = cs.length();
7373 if (start < 0) {
7474 start = 0;
7575 }
9090 * @param start the start index
9191 * @return the index where the search sequence was found
9292 */
93 static int indexOf(CharSequence cs, CharSequence searchChar, int start) {
93 static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) {
9494 return cs.toString().indexOf(searchChar.toString(), start);
9595 // if (cs instanceof String && searchChar instanceof String) {
9696 // // TODO: Do we assume searchChar is usually relatively small;
112112 * @param start the start index, negative returns -1, beyond length starts at end
113113 * @return the index where the search char was found, -1 if not found
114114 */
115 static int lastIndexOf(CharSequence cs, int searchChar, int start) {
115 static int lastIndexOf(final CharSequence cs, final int searchChar, int start) {
116116 if (cs instanceof String) {
117117 return ((String) cs).lastIndexOf(searchChar, start);
118118 } else {
119 int sz = cs.length();
119 final int sz = cs.length();
120120 if (start < 0) {
121121 return -1;
122122 }
140140 * @param start the start index
141141 * @return the index where the search sequence was found
142142 */
143 static int lastIndexOf(CharSequence cs, CharSequence searchChar, int start) {
143 static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, final int start) {
144144 return cs.toString().lastIndexOf(searchChar.toString(), start);
145145 // if (cs instanceof String && searchChar instanceof String) {
146146 // // TODO: Do we assume searchChar is usually relatively small;
159159 * @param cs the {@code CharSequence} to be processed
160160 * @return the resulting char array
161161 */
162 static char[] toCharArray(CharSequence cs) {
162 static char[] toCharArray(final CharSequence cs) {
163163 if (cs instanceof String) {
164164 return ((String) cs).toCharArray();
165165 } else {
166 int sz = cs.length();
167 char[] array = new char[cs.length()];
166 final int sz = cs.length();
167 final char[] array = new char[cs.length()];
168168 for (int i = 0; i < sz; i++) {
169169 array[i] = cs.charAt(i);
170170 }
183183 * @param length character length of the region
184184 * @return whether the region matched
185185 */
186 static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart,
187 CharSequence substring, int start, int length) {
186 static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart,
187 final CharSequence substring, final int start, final int length) {
188188 if (cs instanceof String && substring instanceof String) {
189189 return ((String) cs).regionMatches(ignoreCase, thisStart, (String) substring, start, length);
190190 } else {
191 // TODO: Implement rather than convert to String
192 return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length);
193 }
194 }
195
191 int index1 = thisStart;
192 int index2 = start;
193 int tmpLen = length;
194
195 while (tmpLen-- > 0) {
196 char c1 = cs.charAt(index1++);
197 char c2 = substring.charAt(index2++);
198
199 if (c1 == c2) {
200 continue;
201 }
202
203 if (!ignoreCase) {
204 return false;
205 }
206
207 // The same check as in String.regionMatches():
208 if (Character.toUpperCase(c1) != Character.toUpperCase(c2)
209 && Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
210 return false;
211 }
212 }
213
214 return true;
215 }
216 }
196217 }
2929 *
3030 * <p>#ThreadSafe#</p>
3131 * @since 1.0
32 * @version $Id: CharSet.java 1199894 2011-11-09 17:53:59Z ggregory $
32 * @version $Id: CharSet.java 1436770 2013-01-22 07:09:45Z ggregory $
3333 */
3434 public class CharSet implements Serializable {
3535
134134 * @return a CharSet instance
135135 * @since 2.4
136136 */
137 public static CharSet getInstance(String... setStrs) {
137 public static CharSet getInstance(final String... setStrs) {
138138 if (setStrs == null) {
139139 return null;
140140 }
141141 if (setStrs.length == 1) {
142 CharSet common = COMMON.get(setStrs[0]);
142 final CharSet common = COMMON.get(setStrs[0]);
143143 if (common != null) {
144144 return common;
145145 }
155155 * @param set Strings to merge into the initial set
156156 * @throws NullPointerException if set is {@code null}
157157 */
158 protected CharSet(String... set) {
158 protected CharSet(final String... set) {
159159 super();
160 int sz = set.length;
160 final int sz = set.length;
161161 for (int i = 0; i < sz; i++) {
162162 add(set[i]);
163163 }
169169 *
170170 * @param str set definition string
171171 */
172 protected void add(String str) {
172 protected void add(final String str) {
173173 if (str == null) {
174174 return;
175175 }
176176
177 int len = str.length();
177 final int len = str.length();
178178 int pos = 0;
179179 while (pos < len) {
180 int remainder = len - pos;
180 final int remainder = len - pos;
181181 if (remainder >= 4 && str.charAt(pos) == '^' && str.charAt(pos + 2) == '-') {
182182 // negated range
183183 set.add(CharRange.isNotIn(str.charAt(pos + 1), str.charAt(pos + 3)));
219219 * @param ch the character to check for
220220 * @return {@code true} if the set contains the characters
221221 */
222 public boolean contains(char ch) {
223 for (CharRange range : set) {
222 public boolean contains(final char ch) {
223 for (final CharRange range : set) {
224224 if (range.contains(ch)) {
225225 return true;
226226 }
242242 * @since 2.0
243243 */
244244 @Override
245 public boolean equals(Object obj) {
245 public boolean equals(final Object obj) {
246246 if (obj == this) {
247247 return true;
248248 }
249249 if (obj instanceof CharSet == false) {
250250 return false;
251251 }
252 CharSet other = (CharSet) obj;
252 final CharSet other = (CharSet) obj;
253253 return set.equals(other.set);
254254 }
255255
2525 * <p>#ThreadSafe#</p>
2626 * @see CharSet
2727 * @since 1.0
28 * @version $Id: CharSetUtils.java 1144916 2011-07-10 17:50:21Z ggregory $
28 * @version $Id: CharSetUtils.java 1552679 2013-12-20 14:08:03Z britter $
2929 */
3030 public class CharSetUtils {
3131
6060 * @param set the character set to use for manipulation, may be null
6161 * @return the modified String, {@code null} if null string input
6262 */
63 public static String squeeze(String str, String... set) {
63 public static String squeeze(final String str, final String... set) {
6464 if (StringUtils.isEmpty(str) || deepEmpty(set)) {
6565 return str;
6666 }
67 CharSet chars = CharSet.getInstance(set);
68 StringBuilder buffer = new StringBuilder(str.length());
69 char[] chrs = str.toCharArray();
70 int sz = chrs.length;
67 final CharSet chars = CharSet.getInstance(set);
68 final StringBuilder buffer = new StringBuilder(str.length());
69 final char[] chrs = str.toCharArray();
70 final int sz = chrs.length;
7171 char lastChar = ' ';
7272 char ch = ' ';
7373 for (int i = 0; i < sz; i++) {
8282 return buffer.toString();
8383 }
8484
85 // ContainsAny
86 //-----------------------------------------------------------------------
87 /**
88 * <p>Takes an argument in set-syntax, see evaluateSet,
89 * and identifies whether any of the characters are present in the specified string.</p>
90 *
91 * <pre>
92 * CharSetUtils.containsAny(null, *) = false
93 * CharSetUtils.containsAny("", *) = false
94 * CharSetUtils.containsAny(*, null) = false
95 * CharSetUtils.containsAny(*, "") = false
96 * CharSetUtils.containsAny("hello", "k-p") = true
97 * CharSetUtils.containsAny("hello", "a-d") = false
98 * </pre>
99 *
100 * @see CharSet#getInstance(java.lang.String...) for set-syntax.
101 * @param str String to look for characters in, may be null
102 * @param set String[] set of characters to identify, may be null
103 * @return whether or not the characters in the set are in the primary string
104 * @since 3.2
105 */
106 public static boolean containsAny(final String str, final String... set) {
107 if (StringUtils.isEmpty(str) || deepEmpty(set)) {
108 return false;
109 }
110 final CharSet chars = CharSet.getInstance(set);
111 for (final char c : str.toCharArray()) {
112 if (chars.contains(c)) {
113 return true;
114 }
115 }
116 return false;
117 }
118
85119 // Count
86120 //-----------------------------------------------------------------------
87121 /**
102136 * @param set String[] set of characters to count, may be null
103137 * @return the character count, zero if null string input
104138 */
105 public static int count(String str, String... set) {
139 public static int count(final String str, final String... set) {
106140 if (StringUtils.isEmpty(str) || deepEmpty(set)) {
107141 return 0;
108142 }
109 CharSet chars = CharSet.getInstance(set);
143 final CharSet chars = CharSet.getInstance(set);
110144 int count = 0;
111 for (char c : str.toCharArray()) {
145 for (final char c : str.toCharArray()) {
112146 if (chars.contains(c)) {
113147 count++;
114148 }
137171 * @return the modified String, {@code null} if null string input
138172 * @since 2.0
139173 */
140 public static String keep(String str, String... set) {
174 public static String keep(final String str, final String... set) {
141175 if (str == null) {
142176 return null;
143177 }
144 if (str.length() == 0 || deepEmpty(set)) {
145 return "";
178 if (str.isEmpty() || deepEmpty(set)) {
179 return StringUtils.EMPTY;
146180 }
147181 return modify(str, set, true);
148182 }
167201 * @param set String[] set of characters to delete, may be null
168202 * @return the modified String, {@code null} if null string input
169203 */
170 public static String delete(String str, String... set) {
204 public static String delete(final String str, final String... set) {
171205 if (StringUtils.isEmpty(str) || deepEmpty(set)) {
172206 return str;
173207 }
183217 * @param expect whether to evaluate on match, or non-match
184218 * @return the modified String, not null
185219 */
186 private static String modify(String str, String[] set, boolean expect) {
187 CharSet chars = CharSet.getInstance(set);
188 StringBuilder buffer = new StringBuilder(str.length());
189 char[] chrs = str.toCharArray();
190 int sz = chrs.length;
220 private static String modify(final String str, final String[] set, final boolean expect) {
221 final CharSet chars = CharSet.getInstance(set);
222 final StringBuilder buffer = new StringBuilder(str.length());
223 final char[] chrs = str.toCharArray();
224 final int sz = chrs.length;
191225 for(int i=0; i<sz; i++) {
192226 if(chars.contains(chrs[i]) == expect) {
193227 buffer.append(chrs[i]);
203237 * @param strings String[] whose elements are being checked for emptiness
204238 * @return whether or not the String is empty
205239 */
206 private static boolean deepEmpty(String[] strings) {
240 private static boolean deepEmpty(final String[] strings) {
207241 if (strings != null) {
208 for (String s : strings) {
242 for (final String s : strings) {
209243 if (StringUtils.isNotEmpty(s)) {
210244 return false;
211245 }
2424 *
2525 * <p>#ThreadSafe#</p>
2626 * @since 2.1
27 * @version $Id: CharUtils.java 1158279 2011-08-16 14:06:45Z ggregory $
27 * @version $Id: CharUtils.java 1531257 2013-10-11 11:25:28Z britter $
2828 */
2929 public class CharUtils {
3030
3333 /**
3434 * {@code \u000a} linefeed LF ('\n').
3535 *
36 * @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089">JLF: Escape Sequences
36 * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
3737 * for Character and String Literals</a>
3838 * @since 2.2
3939 */
4242 /**
4343 * {@code \u000d} carriage return CR ('\r').
4444 *
45 * @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089">JLF: Escape Sequences
45 * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
4646 * for Character and String Literals</a>
4747 * @since 2.2
4848 */
8383 * @return a Character of the specified character
8484 */
8585 @Deprecated
86 public static Character toCharacterObject(char ch) {
86 public static Character toCharacterObject(final char ch) {
8787 return Character.valueOf(ch);
8888 }
8989
104104 * @param str the character to convert
105105 * @return the Character value of the first letter of the String
106106 */
107 public static Character toCharacterObject(String str) {
107 public static Character toCharacterObject(final String str) {
108108 if (StringUtils.isEmpty(str)) {
109109 return null;
110110 }
125125 * @return the char value of the Character
126126 * @throws IllegalArgumentException if the Character is null
127127 */
128 public static char toChar(Character ch) {
128 public static char toChar(final Character ch) {
129129 if (ch == null) {
130130 throw new IllegalArgumentException("The Character must not be null");
131131 }
145145 * @param defaultValue the value to use if the Character is null
146146 * @return the char value of the Character or the default if null
147147 */
148 public static char toChar(Character ch, char defaultValue) {
148 public static char toChar(final Character ch, final char defaultValue) {
149149 if (ch == null) {
150150 return defaultValue;
151151 }
168168 * @return the char value of the first letter of the String
169169 * @throws IllegalArgumentException if the String is empty
170170 */
171 public static char toChar(String str) {
171 public static char toChar(final String str) {
172172 if (StringUtils.isEmpty(str)) {
173173 throw new IllegalArgumentException("The String must not be empty");
174174 }
190190 * @param defaultValue the value to use if the Character is null
191191 * @return the char value of the first letter of the String or the default if null
192192 */
193 public static char toChar(String str, char defaultValue) {
193 public static char toChar(final String str, final char defaultValue) {
194194 if (StringUtils.isEmpty(str)) {
195195 return defaultValue;
196196 }
213213 * @return the int value of the character
214214 * @throws IllegalArgumentException if the character is not ASCII numeric
215215 */
216 public static int toIntValue(char ch) {
216 public static int toIntValue(final char ch) {
217217 if (isAsciiNumeric(ch) == false) {
218218 throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'");
219219 }
235235 * @param defaultValue the default value to use if the character is not numeric
236236 * @return the int value of the character
237237 */
238 public static int toIntValue(char ch, int defaultValue) {
238 public static int toIntValue(final char ch, final int defaultValue) {
239239 if (isAsciiNumeric(ch) == false) {
240240 return defaultValue;
241241 }
258258 * @return the int value of the character
259259 * @throws IllegalArgumentException if the Character is not ASCII numeric or is null
260260 */
261 public static int toIntValue(Character ch) {
261 public static int toIntValue(final Character ch) {
262262 if (ch == null) {
263263 throw new IllegalArgumentException("The character must not be null");
264264 }
281281 * @param defaultValue the default value to use if the character is not numeric
282282 * @return the int value of the character
283283 */
284 public static int toIntValue(Character ch, int defaultValue) {
284 public static int toIntValue(final Character ch, final int defaultValue) {
285285 if (ch == null) {
286286 return defaultValue;
287287 }
303303 * @param ch the character to convert
304304 * @return a String containing the one specified character
305305 */
306 public static String toString(char ch) {
306 public static String toString(final char ch) {
307307 if (ch < 128) {
308308 return CHAR_STRING_ARRAY[ch];
309309 }
327327 * @param ch the character to convert
328328 * @return a String containing the one specified character
329329 */
330 public static String toString(Character ch) {
330 public static String toString(final Character ch) {
331331 if (ch == null) {
332332 return null;
333333 }
348348 * @param ch the character to convert
349349 * @return the escaped Unicode string
350350 */
351 public static String unicodeEscaped(char ch) {
351 public static String unicodeEscaped(final char ch) {
352352 if (ch < 0x10) {
353353 return "\\u000" + Integer.toHexString(ch);
354354 } else if (ch < 0x100) {
375375 * @param ch the character to convert, may be null
376376 * @return the escaped Unicode string, null if null input
377377 */
378 public static String unicodeEscaped(Character ch) {
378 public static String unicodeEscaped(final Character ch) {
379379 if (ch == null) {
380380 return null;
381381 }
398398 * @param ch the character to check
399399 * @return true if less than 128
400400 */
401 public static boolean isAscii(char ch) {
401 public static boolean isAscii(final char ch) {
402402 return ch < 128;
403403 }
404404
417417 * @param ch the character to check
418418 * @return true if between 32 and 126 inclusive
419419 */
420 public static boolean isAsciiPrintable(char ch) {
420 public static boolean isAsciiPrintable(final char ch) {
421421 return ch >= 32 && ch < 127;
422422 }
423423
436436 * @param ch the character to check
437437 * @return true if less than 32 or equals 127
438438 */
439 public static boolean isAsciiControl(char ch) {
439 public static boolean isAsciiControl(final char ch) {
440440 return ch < 32 || ch == 127;
441441 }
442442
455455 * @param ch the character to check
456456 * @return true if between 65 and 90 or 97 and 122 inclusive
457457 */
458 public static boolean isAsciiAlpha(char ch) {
459 return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
458 public static boolean isAsciiAlpha(final char ch) {
459 return isAsciiAlphaUpper(ch) || isAsciiAlphaLower(ch);
460460 }
461461
462462 /**
474474 * @param ch the character to check
475475 * @return true if between 65 and 90 inclusive
476476 */
477 public static boolean isAsciiAlphaUpper(char ch) {
477 public static boolean isAsciiAlphaUpper(final char ch) {
478478 return ch >= 'A' && ch <= 'Z';
479479 }
480480
493493 * @param ch the character to check
494494 * @return true if between 97 and 122 inclusive
495495 */
496 public static boolean isAsciiAlphaLower(char ch) {
496 public static boolean isAsciiAlphaLower(final char ch) {
497497 return ch >= 'a' && ch <= 'z';
498498 }
499499
512512 * @param ch the character to check
513513 * @return true if between 48 and 57 inclusive
514514 */
515 public static boolean isAsciiNumeric(char ch) {
515 public static boolean isAsciiNumeric(final char ch) {
516516 return ch >= '0' && ch <= '9';
517517 }
518518
531531 * @param ch the character to check
532532 * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
533533 */
534 public static boolean isAsciiAlphanumeric(char ch) {
535 return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
534 public static boolean isAsciiAlphanumeric(final char ch) {
535 return isAsciiAlpha(ch) || isAsciiNumeric(ch);
536536 }
537537
538538 }
1818 import java.lang.reflect.Method;
1919 import java.lang.reflect.Modifier;
2020 import java.util.ArrayList;
21 import java.util.Collections;
2122 import java.util.HashMap;
2223 import java.util.HashSet;
24 import java.util.Iterator;
2325 import java.util.LinkedHashSet;
2426 import java.util.List;
2527 import java.util.Map;
26
28 import java.util.Set;
29
30 import org.apache.commons.lang3.mutable.MutableObject;
2731
2832 /**
2933 * <p>Operates on classes without using reflection.</p>
3741 * {@code [I}. </p>
3842 *
3943 * @since 2.0
40 * @version $Id: ClassUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
44 * @version $Id: ClassUtils.java 1534839 2013-10-22 22:48:58Z mbenson $
4145 */
4246 public class ClassUtils {
43
44 /**
45 * <p>The package separator character: <code>'&#x2e;' == {@value}</code>.</p>
47 /**
48 * Inclusivity literals for {@link #hierarchy(Class, Interfaces)}.
49 * @since 3.2
50 */
51 public enum Interfaces {
52 INCLUDE, EXCLUDE;
53 }
54
55 /**
56 * The package separator character: <code>'&#x2e;' == {@value}</code>.
4657 */
4758 public static final char PACKAGE_SEPARATOR_CHAR = '.';
4859
4960 /**
50 * <p>The package separator String: {@code "&#x2e;"}.</p>
61 * The package separator String: <code>"&#x2e;"</code>.
5162 */
5263 public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);
5364
5465 /**
55 * <p>The inner class separator character: <code>'$' == {@value}</code>.</p>
66 * The inner class separator character: <code>'$' == {@value}</code>.
5667 */
5768 public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
5869
5970 /**
60 * <p>The inner class separator String: {@code "$"}.</p>
71 * The inner class separator String: {@code "$"}.
6172 */
6273 public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);
6374
8293 */
8394 private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>();
8495 static {
85 for (Class<?> primitiveClass : primitiveWrapperMap.keySet()) {
86 Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
96 for (final Class<?> primitiveClass : primitiveWrapperMap.keySet()) {
97 final Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
8798 if (!primitiveClass.equals(wrapperClass)) {
8899 wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
89100 }
93104 /**
94105 * Maps a primitive class name to its corresponding abbreviation used in array class names.
95106 */
96 private static final Map<String, String> abbreviationMap = new HashMap<String, String>();
107 private static final Map<String, String> abbreviationMap;
97108
98109 /**
99110 * Maps an abbreviation used in array class names to corresponding primitive class name.
100111 */
101 private static final Map<String, String> reverseAbbreviationMap = new HashMap<String, String>();
102
103 /**
104 * Add primitive type abbreviation to maps of abbreviations.
105 *
106 * @param primitive Canonical name of primitive type
107 * @param abbreviation Corresponding abbreviation of primitive type
108 */
109 private static void addAbbreviation(String primitive, String abbreviation) {
110 abbreviationMap.put(primitive, abbreviation);
111 reverseAbbreviationMap.put(abbreviation, primitive);
112 }
112 private static final Map<String, String> reverseAbbreviationMap;
113113
114114 /**
115115 * Feed abbreviation maps
116116 */
117117 static {
118 addAbbreviation("int", "I");
119 addAbbreviation("boolean", "Z");
120 addAbbreviation("float", "F");
121 addAbbreviation("long", "J");
122 addAbbreviation("short", "S");
123 addAbbreviation("byte", "B");
124 addAbbreviation("double", "D");
125 addAbbreviation("char", "C");
118 final Map<String, String> m = new HashMap<String, String>();
119 m.put("int", "I");
120 m.put("boolean", "Z");
121 m.put("float", "F");
122 m.put("long", "J");
123 m.put("short", "S");
124 m.put("byte", "B");
125 m.put("double", "D");
126 m.put("char", "C");
127 m.put("void", "V");
128 final Map<String, String> r = new HashMap<String, String>();
129 for (Map.Entry<String, String> e : m.entrySet()) {
130 r.put(e.getValue(), e.getKey());
131 }
132 abbreviationMap = Collections.unmodifiableMap(m);
133 reverseAbbreviationMap = Collections.unmodifiableMap(r);
126134 }
127135
128136 /**
146154 * @param valueIfNull the value to return if null
147155 * @return the class name of the object without the package name, or the null value
148156 */
149 public static String getShortClassName(Object object, String valueIfNull) {
157 public static String getShortClassName(final Object object, final String valueIfNull) {
150158 if (object == null) {
151159 return valueIfNull;
152160 }
155163
156164 /**
157165 * <p>Gets the class name minus the package name from a {@code Class}.</p>
158 *
159 * <p>Consider using the Java 5 API {@link Class#getSimpleName()} instead.
160 * The one known difference is that this code will return {@code "Map.Entry"} while
166 *
167 * <p>Consider using the Java 5 API {@link Class#getSimpleName()} instead.
168 * The one known difference is that this code will return {@code "Map.Entry"} while
161169 * the {@code java.lang.Class} variant will simply return {@code "Entry"}. </p>
162170 *
163171 * @param cls the class to get the short name for.
164172 * @return the class name without the package name or an empty string
165173 */
166 public static String getShortClassName(Class<?> cls) {
174 public static String getShortClassName(final Class<?> cls) {
167175 if (cls == null) {
168176 return StringUtils.EMPTY;
169177 }
175183 *
176184 * <p>The string passed in is assumed to be a class name - it is not checked.</p>
177185
178 * <p>Note that this method differs from Class.getSimpleName() in that this will
179 * return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply
186 * <p>Note that this method differs from Class.getSimpleName() in that this will
187 * return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply
180188 * return {@code "Entry"}. </p>
181189 *
182190 * @param className the className to get the short name for
183191 * @return the class name of the class without the package name or an empty string
184192 */
185193 public static String getShortClassName(String className) {
186 if (className == null) {
194 if (StringUtils.isEmpty(className)) {
187195 return StringUtils.EMPTY;
188196 }
189 if (className.length() == 0) {
190 return StringUtils.EMPTY;
191 }
192
193 StringBuilder arrayPrefix = new StringBuilder();
197
198 final StringBuilder arrayPrefix = new StringBuilder();
194199
195200 // Handle array encoding
196201 if (className.startsWith("[")) {
202207 if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
203208 className = className.substring(1, className.length() - 1);
204209 }
205 }
206
207 if (reverseAbbreviationMap.containsKey(className)) {
208 className = reverseAbbreviationMap.get(className);
209 }
210
211 int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
212 int innerIdx = className.indexOf(
210
211 if (reverseAbbreviationMap.containsKey(className)) {
212 className = reverseAbbreviationMap.get(className);
213 }
214 }
215
216 final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
217 final int innerIdx = className.indexOf(
213218 INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
214219 String out = className.substring(lastDotIdx + 1);
215220 if (innerIdx != -1) {
226231 * @since 3.0
227232 * @see Class#getSimpleName()
228233 */
229 public static String getSimpleName(Class<?> cls) {
234 public static String getSimpleName(final Class<?> cls) {
230235 if (cls == null) {
231236 return StringUtils.EMPTY;
232237 }
242247 * @since 3.0
243248 * @see Class#getSimpleName()
244249 */
245 public static String getSimpleName(Object object, String valueIfNull) {
250 public static String getSimpleName(final Object object, final String valueIfNull) {
246251 if (object == null) {
247252 return valueIfNull;
248253 }
258263 * @param valueIfNull the value to return if null
259264 * @return the package name of the object, or the null value
260265 */
261 public static String getPackageName(Object object, String valueIfNull) {
266 public static String getPackageName(final Object object, final String valueIfNull) {
262267 if (object == null) {
263268 return valueIfNull;
264269 }
271276 * @param cls the class to get the package name for, may be {@code null}.
272277 * @return the package name or an empty string
273278 */
274 public static String getPackageName(Class<?> cls) {
279 public static String getPackageName(final Class<?> cls) {
275280 if (cls == null) {
276281 return StringUtils.EMPTY;
277282 }
288293 * @return the package name or an empty string
289294 */
290295 public static String getPackageName(String className) {
291 if (className == null || className.length() == 0) {
296 if (StringUtils.isEmpty(className)) {
292297 return StringUtils.EMPTY;
293298 }
294299
301306 className = className.substring(1);
302307 }
303308
304 int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
309 final int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
305310 if (i == -1) {
306311 return StringUtils.EMPTY;
307312 }
317322 * @return the {@code List} of superclasses in order going up from this one
318323 * {@code null} if null input
319324 */
320 public static List<Class<?>> getAllSuperclasses(Class<?> cls) {
325 public static List<Class<?>> getAllSuperclasses(final Class<?> cls) {
321326 if (cls == null) {
322327 return null;
323328 }
324 List<Class<?>> classes = new ArrayList<Class<?>>();
329 final List<Class<?>> classes = new ArrayList<Class<?>>();
325330 Class<?> superclass = cls.getSuperclass();
326331 while (superclass != null) {
327332 classes.add(superclass);
343348 * @return the {@code List} of interfaces in order,
344349 * {@code null} if null input
345350 */
346 public static List<Class<?>> getAllInterfaces(Class<?> cls) {
351 public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
347352 if (cls == null) {
348353 return null;
349354 }
350355
351 LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>();
356 final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>();
352357 getAllInterfaces(cls, interfacesFound);
353358
354359 return new ArrayList<Class<?>>(interfacesFound);
360365 * @param cls the class to look up, may be {@code null}
361366 * @param interfacesFound the {@code Set} of interfaces for the class
362367 */
363 private static void getAllInterfaces(Class<?> cls, HashSet<Class<?>> interfacesFound) {
368 private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {
364369 while (cls != null) {
365 Class<?>[] interfaces = cls.getInterfaces();
366
367 for (Class<?> i : interfaces) {
370 final Class<?>[] interfaces = cls.getInterfaces();
371
372 for (final Class<?> i : interfaces) {
368373 if (interfacesFound.add(i)) {
369374 getAllInterfaces(i, interfacesFound);
370375 }
388393 * {@code null} if null input
389394 * @throws ClassCastException if classNames contains a non String entry
390395 */
391 public static List<Class<?>> convertClassNamesToClasses(List<String> classNames) {
396 public static List<Class<?>> convertClassNamesToClasses(final List<String> classNames) {
392397 if (classNames == null) {
393398 return null;
394399 }
395 List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size());
396 for (String className : classNames) {
400 final List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size());
401 for (final String className : classNames) {
397402 try {
398403 classes.add(Class.forName(className));
399 } catch (Exception ex) {
404 } catch (final Exception ex) {
400405 classes.add(null);
401406 }
402407 }
415420 * {@code null} if null input
416421 * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry
417422 */
418 public static List<String> convertClassesToClassNames(List<Class<?>> classes) {
423 public static List<String> convertClassesToClassNames(final List<Class<?>> classes) {
419424 if (classes == null) {
420425 return null;
421426 }
422 List<String> classNames = new ArrayList<String>(classes.size());
423 for (Class<?> cls : classes) {
427 final List<String> classNames = new ArrayList<String>(classes.size());
428 for (final Class<?> cls : classes) {
424429 if (cls == null) {
425430 classNames.add(null);
426431 } else {
456461 * specified {@code Class} parameter can be converted to the type
457462 * represented by this {@code Class} object via an identity conversion
458463 * widening primitive or widening reference conversion. See
459 * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
464 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
460465 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
461466 *
462467 * <p><strong>Since Lang 3.0,</strong> this method will default behavior for
468473 * @param toClassArray the array of Classes to try to assign into, may be {@code null}
469474 * @return {@code true} if assignment possible
470475 */
471 public static boolean isAssignable(Class<?>[] classArray, Class<?>... toClassArray) {
476 public static boolean isAssignable(final Class<?>[] classArray, final Class<?>... toClassArray) {
472477 return isAssignable(classArray, toClassArray, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
473478 }
474479
496501 * specified {@code Class} parameter can be converted to the type
497502 * represented by this {@code Class} object via an identity conversion
498503 * widening primitive or widening reference conversion. See
499 * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
504 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
500505 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
501506 *
502507 * @param classArray the array of Classes to check, may be {@code null}
504509 * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
505510 * @return {@code true} if assignment possible
506511 */
507 public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, boolean autoboxing) {
512 public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, final boolean autoboxing) {
508513 if (ArrayUtils.isSameLength(classArray, toClassArray) == false) {
509514 return false;
510515 }
525530 /**
526531 * Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
527532 * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
528 *
533 *
529534 * @param type
530535 * The class to query or null.
531536 * @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
532537 * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
533538 * @since 3.1
534539 */
535 public static boolean isPrimitiveOrWrapper(Class<?> type) {
540 public static boolean isPrimitiveOrWrapper(final Class<?> type) {
536541 if (type == null) {
537542 return false;
538543 }
542547 /**
543548 * Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
544549 * {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
545 *
550 *
546551 * @param type
547552 * The class to query or null.
548553 * @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
549554 * {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
550555 * @since 3.1
551556 */
552 public static boolean isPrimitiveWrapper(Class<?> type) {
557 public static boolean isPrimitiveWrapper(final Class<?> type) {
553558 return wrapperPrimitiveMap.containsKey(type);
554559 }
555560
572577 * specified {@code Class} parameter can be converted to the type
573578 * represented by this {@code Class} object via an identity conversion
574579 * widening primitive or widening reference conversion. See
575 * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
580 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
576581 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
577582 *
578583 * <p><strong>Since Lang 3.0,</strong> this method will default behavior for
584589 * @param toClass the Class to try to assign into, returns false if null
585590 * @return {@code true} if assignment possible
586591 */
587 public static boolean isAssignable(Class<?> cls, Class<?> toClass) {
592 public static boolean isAssignable(final Class<?> cls, final Class<?> toClass) {
588593 return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
589594 }
590595
607612 * specified {@code Class} parameter can be converted to the type
608613 * represented by this {@code Class} object via an identity conversion
609614 * widening primitive or widening reference conversion. See
610 * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
615 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
611616 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
612617 *
613618 * @param cls the Class to check, may be null
615620 * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
616621 * @return {@code true} if assignment possible
617622 */
618 public static boolean isAssignable(Class<?> cls, Class<?> toClass, boolean autoboxing) {
623 public static boolean isAssignable(Class<?> cls, final Class<?> toClass, final boolean autoboxing) {
619624 if (toClass == null) {
620625 return false;
621626 }
700705 * {@code cls} is not a primitive. {@code null} if null input.
701706 * @since 2.1
702707 */
703 public static Class<?> primitiveToWrapper(Class<?> cls) {
708 public static Class<?> primitiveToWrapper(final Class<?> cls) {
704709 Class<?> convertedClass = cls;
705710 if (cls != null && cls.isPrimitive()) {
706711 convertedClass = primitiveWrapperMap.get(cls);
718723 * Empty array if an empty array passed in.
719724 * @since 2.1
720725 */
721 public static Class<?>[] primitivesToWrappers(Class<?>... classes) {
726 public static Class<?>[] primitivesToWrappers(final Class<?>... classes) {
722727 if (classes == null) {
723728 return null;
724729 }
727732 return classes;
728733 }
729734
730 Class<?>[] convertedClasses = new Class[classes.length];
735 final Class<?>[] convertedClasses = new Class[classes.length];
731736 for (int i = 0; i < classes.length; i++) {
732737 convertedClasses[i] = primitiveToWrapper(classes[i]);
733738 }
750755 * @see #primitiveToWrapper(Class)
751756 * @since 2.4
752757 */
753 public static Class<?> wrapperToPrimitive(Class<?> cls) {
758 public static Class<?> wrapperToPrimitive(final Class<?> cls) {
754759 return wrapperPrimitiveMap.get(cls);
755760 }
756761
768773 * @see #wrapperToPrimitive(Class)
769774 * @since 2.4
770775 */
771 public static Class<?>[] wrappersToPrimitives(Class<?>... classes) {
776 public static Class<?>[] wrappersToPrimitives(final Class<?>... classes) {
772777 if (classes == null) {
773778 return null;
774779 }
777782 return classes;
778783 }
779784
780 Class<?>[] convertedClasses = new Class[classes.length];
785 final Class<?>[] convertedClasses = new Class[classes.length];
781786 for (int i = 0; i < classes.length; i++) {
782787 convertedClasses[i] = wrapperToPrimitive(classes[i]);
783788 }
793798 * @return {@code true} if the class is an inner or static nested class,
794799 * false if not or {@code null}
795800 */
796 public static boolean isInnerClass(Class<?> cls) {
801 public static boolean isInnerClass(final Class<?> cls) {
797802 return cls != null && cls.getEnclosingClass() != null;
798803 }
799804
812817 * @throws ClassNotFoundException if the class is not found
813818 */
814819 public static Class<?> getClass(
815 ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException {
820 final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
816821 try {
817822 Class<?> clazz;
818823 if (abbreviationMap.containsKey(className)) {
819 String clsName = "[" + abbreviationMap.get(className);
824 final String clsName = "[" + abbreviationMap.get(className);
820825 clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
821826 } else {
822827 clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
823828 }
824829 return clazz;
825 } catch (ClassNotFoundException ex) {
830 } catch (final ClassNotFoundException ex) {
826831 // allow path separators (.) as inner class name separators
827 int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
832 final int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
828833
829834 if (lastDotIndex != -1) {
830835 try {
831836 return getClass(classLoader, className.substring(0, lastDotIndex) +
832837 INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
833838 initialize);
834 } catch (ClassNotFoundException ex2) { // NOPMD
839 } catch (final ClassNotFoundException ex2) { // NOPMD
835840 // ignore exception
836841 }
837842 }
852857 * @return the class represented by {@code className} using the {@code classLoader}
853858 * @throws ClassNotFoundException if the class is not found
854859 */
855 public static Class<?> getClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
860 public static Class<?> getClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException {
856861 return getClass(classLoader, className, true);
857862 }
858863
867872 * @return the class represented by {@code className} using the current thread's context class loader
868873 * @throws ClassNotFoundException if the class is not found
869874 */
870 public static Class<?> getClass(String className) throws ClassNotFoundException {
875 public static Class<?> getClass(final String className) throws ClassNotFoundException {
871876 return getClass(className, true);
872877 }
873878
882887 * @return the class represented by {@code className} using the current thread's context class loader
883888 * @throws ClassNotFoundException if the class is not found
884889 */
885 public static Class<?> getClass(String className, boolean initialize) throws ClassNotFoundException {
886 ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
887 ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
890 public static Class<?> getClass(final String className, final boolean initialize) throws ClassNotFoundException {
891 final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
892 final ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
888893 return getClass(loader, className, initialize);
889894 }
890895
907912 * @param parameterTypes the list of parameters
908913 * @return the method
909914 * @throws NullPointerException if the class is null
910 * @throws SecurityException if a a security violation occured
915 * @throws SecurityException if a security violation occurred
911916 * @throws NoSuchMethodException if the method is not found in the given class
912917 * or if the metothod doen't conform with the requirements
913918 */
914 public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>... parameterTypes)
919 public static Method getPublicMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes)
915920 throws SecurityException, NoSuchMethodException {
916921
917 Method declaredMethod = cls.getMethod(methodName, parameterTypes);
922 final Method declaredMethod = cls.getMethod(methodName, parameterTypes);
918923 if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
919924 return declaredMethod;
920925 }
921926
922 List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
927 final List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
923928 candidateClasses.addAll(getAllInterfaces(cls));
924929 candidateClasses.addAll(getAllSuperclasses(cls));
925930
926 for (Class<?> candidateClass : candidateClasses) {
931 for (final Class<?> candidateClass : candidateClasses) {
927932 if (!Modifier.isPublic(candidateClass.getModifiers())) {
928933 continue;
929934 }
930935 Method candidateMethod;
931936 try {
932937 candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
933 } catch (NoSuchMethodException ex) {
938 } catch (final NoSuchMethodException ex) {
934939 continue;
935940 }
936941 if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
954959 if (className == null) {
955960 throw new NullPointerException("className must not be null.");
956961 } else if (className.endsWith("[]")) {
957 StringBuilder classNameBuffer = new StringBuilder();
962 final StringBuilder classNameBuffer = new StringBuilder();
958963 while (className.endsWith("[]")) {
959964 className = className.substring(0, className.length() - 2);
960965 classNameBuffer.append("[");
961966 }
962 String abbreviation = abbreviationMap.get(className);
967 final String abbreviation = abbreviationMap.get(className);
963968 if (abbreviation != null) {
964969 classNameBuffer.append(abbreviation);
965970 } else {
980985 * @return a {@code Class} array, {@code null} if null array input
981986 * @since 2.4
982987 */
983 public static Class<?>[] toClass(Object... array) {
988 public static Class<?>[] toClass(final Object... array) {
984989 if (array == null) {
985990 return null;
986991 } else if (array.length == 0) {
987992 return ArrayUtils.EMPTY_CLASS_ARRAY;
988993 }
989 Class<?>[] classes = new Class[array.length];
994 final Class<?>[] classes = new Class[array.length];
990995 for (int i = 0; i < array.length; i++) {
991996 classes[i] = array[i] == null ? null : array[i].getClass();
992997 }
10031008 * @return the canonical name of the object without the package name, or the null value
10041009 * @since 2.4
10051010 */
1006 public static String getShortCanonicalName(Object object, String valueIfNull) {
1011 public static String getShortCanonicalName(final Object object, final String valueIfNull) {
10071012 if (object == null) {
10081013 return valueIfNull;
10091014 }
10171022 * @return the canonical name without the package name or an empty string
10181023 * @since 2.4
10191024 */
1020 public static String getShortCanonicalName(Class<?> cls) {
1025 public static String getShortCanonicalName(final Class<?> cls) {
10211026 if (cls == null) {
10221027 return StringUtils.EMPTY;
10231028 }
10331038 * @return the canonical name of the class without the package name or an empty string
10341039 * @since 2.4
10351040 */
1036 public static String getShortCanonicalName(String canonicalName) {
1041 public static String getShortCanonicalName(final String canonicalName) {
10371042 return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
10381043 }
10391044
10471052 * @return the package name of the object, or the null value
10481053 * @since 2.4
10491054 */
1050 public static String getPackageCanonicalName(Object object, String valueIfNull) {
1055 public static String getPackageCanonicalName(final Object object, final String valueIfNull) {
10511056 if (object == null) {
10521057 return valueIfNull;
10531058 }
10611066 * @return the package name or an empty string
10621067 * @since 2.4
10631068 */
1064 public static String getPackageCanonicalName(Class<?> cls) {
1069 public static String getPackageCanonicalName(final Class<?> cls) {
10651070 if (cls == null) {
10661071 return StringUtils.EMPTY;
10671072 }
10781083 * @return the package name or an empty string
10791084 * @since 2.4
10801085 */
1081 public static String getPackageCanonicalName(String canonicalName) {
1086 public static String getPackageCanonicalName(final String canonicalName) {
10821087 return ClassUtils.getPackageName(getCanonicalName(canonicalName));
10831088 }
10841089
11221127 className = reverseAbbreviationMap.get(className.substring(0, 1));
11231128 }
11241129 }
1125 StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
1130 final StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
11261131 for (int i = 0; i < dim; i++) {
11271132 canonicalClassNameBuffer.append("[]");
11281133 }
11311136 }
11321137 }
11331138
1139 /**
1140 * Get an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order,
1141 * excluding interfaces.
1142 *
1143 * @param type the type to get the class hierarchy from
1144 * @return Iterable an Iterable over the class hierarchy of the given class
1145 * @since 3.2
1146 */
1147 public static Iterable<Class<?>> hierarchy(final Class<?> type) {
1148 return hierarchy(type, Interfaces.EXCLUDE);
1149 }
1150
1151 /**
1152 * Get an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order.
1153 *
1154 * @param type the type to get the class hierarchy from
1155 * @param interfacesBehavior switch indicating whether to include or exclude interfaces
1156 * @return Iterable an Iterable over the class hierarchy of the given class
1157 * @since 3.2
1158 */
1159 public static Iterable<Class<?>> hierarchy(final Class<?> type, Interfaces interfacesBehavior) {
1160 final Iterable<Class<?>> classes = new Iterable<Class<?>>() {
1161
1162 @Override
1163 public Iterator<Class<?>> iterator() {
1164 final MutableObject<Class<?>> next = new MutableObject<Class<?>>(type);
1165 return new Iterator<Class<?>>() {
1166
1167 @Override
1168 public boolean hasNext() {
1169 return next.getValue() != null;
1170 }
1171
1172 @Override
1173 public Class<?> next() {
1174 final Class<?> result = next.getValue();
1175 next.setValue(result.getSuperclass());
1176 return result;
1177 }
1178
1179 @Override
1180 public void remove() {
1181 throw new UnsupportedOperationException();
1182 }
1183
1184 };
1185 }
1186
1187 };
1188 if (interfacesBehavior != Interfaces.INCLUDE) {
1189 return classes;
1190 }
1191 return new Iterable<Class<?>>() {
1192
1193 @Override
1194 public Iterator<Class<?>> iterator() {
1195 final Set<Class<?>> seenInterfaces = new HashSet<Class<?>>();
1196 final Iterator<Class<?>> wrapped = classes.iterator();
1197
1198 return new Iterator<Class<?>>() {
1199 Iterator<Class<?>> interfaces = Collections.<Class<?>> emptySet().iterator();
1200
1201 @Override
1202 public boolean hasNext() {
1203 return interfaces.hasNext() || wrapped.hasNext();
1204 }
1205
1206 @Override
1207 public Class<?> next() {
1208 if (interfaces.hasNext()) {
1209 final Class<?> nextInterface = interfaces.next();
1210 seenInterfaces.add(nextInterface);
1211 return nextInterface;
1212 }
1213 final Class<?> nextSuperclass = wrapped.next();
1214 final Set<Class<?>> currentInterfaces = new LinkedHashSet<Class<?>>();
1215 walkInterfaces(currentInterfaces, nextSuperclass);
1216 interfaces = currentInterfaces.iterator();
1217 return nextSuperclass;
1218 }
1219
1220 private void walkInterfaces(Set<Class<?>> addTo, Class<?> c) {
1221 for (Class<?> iface : c.getInterfaces()) {
1222 if (!seenInterfaces.contains(iface)) {
1223 addTo.add(iface);
1224 }
1225 walkInterfaces(addTo, iface);
1226 }
1227 }
1228
1229 @Override
1230 public void remove() {
1231 throw new UnsupportedOperationException();
1232 }
1233
1234 };
1235 }
1236 };
1237 }
1238
11341239 }
0 /*******************************************************************************
1 * Licensed to the Apache Software Foundation (ASF) under one
2 * or more contributor license agreements. See the NOTICE file
3 * distributed with this work for additional information
4 * regarding copyright ownership. The ASF licenses this file
5 * to you under the Apache License, Version 2.0 (the
6 * "License"); you may not use this file except in compliance
7 * with the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing,
12 * software distributed under the License is distributed on an
13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 * KIND, either express or implied. See the License for the
15 * specific language governing permissions and limitations
16 * under the License.
17 *******************************************************************************/
18 package org.apache.commons.lang3;
19
20 import java.util.UUID;
21
22
23 /**
24 * <p>
25 * Static methods to convert a type into another, with endianness and bit ordering awareness.
26 * </p>
27 * <p>
28 * The methods names follow a naming rule:</br>
29 * {@code <source type>[source endianness][source bit ordering]To<destination type>[destination endianness][destination bit ordering]}
30 * </p>
31 * <p>
32 * Source/destination type fields is one of the following:
33 * <ul>
34 * <li>binary: an array of booleans</li>
35 * <li>byte or byteArray</li>
36 * <li>int or intArray</li>
37 * <li>long or longArray</li>
38 * <li>hex: a String containing hexadecimal digits (lowercase in destination)</li>
39 * <li>hexDigit: a Char containing a hexadecimal digit (lowercase in destination)</li>
40 * <li>uuid</li>
41 * </ul>
42 * Endianness field: little endian is the default, in this case the field is absent. In case of
43 * big endian, the field is "Be".</br> Bit ordering: Lsb0 is the default, in this case the field
44 * is absent. In case of Msb0, the field is "Msb0".
45 * </p>
46 * <p>
47 * Example: intBeMsb0ToHex convert an int with big endian byte order and Msb0 bit order into its
48 * hexadecimal string representation
49 * </p>
50 * <p>
51 * Most of the methods provide only default encoding for destination, this limits the number of
52 * ways to do one thing. Unless you are dealing with data from/to outside of the JVM platform,
53 * you should not need to use "Be" and "Msb0" methods.
54 * </p>
55 * <p>
56 * Development status: work on going, only a part of the little endian, Lsb0 methods implemented
57 * so far.
58 * </p>
59 *
60 * @since Lang 3.2
61 * @version $Id: Conversion.java 1436770 2013-01-22 07:09:45Z ggregory $
62 */
63
64 public class Conversion {
65 /**
66 * <p>
67 * Converts a hexadecimal digit into an int using the default (Lsb0) bit ordering.
68 * </p>
69 * <p>
70 * '1' is converted to 1
71 * </p>
72 *
73 * @param hexDigit the hexadecimal digit to convert
74 * @return an int equals to {@code hexDigit}
75 * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
76 */
77 public static int hexDigitToInt(final char hexDigit) {
78 final int digit = Character.digit(hexDigit, 16);
79 if (digit < 0) {
80 throw new IllegalArgumentException("Cannot interpret '"
81 + hexDigit
82 + "' as a hexadecimal digit");
83 }
84 return digit;
85 }
86
87 /**
88 * <p>
89 * Converts a hexadecimal digit into an int using the Msb0 bit ordering.
90 * </p>
91 * <p>
92 * '1' is converted to 8
93 * </p>
94 *
95 * @param hexDigit the hexadecimal digit to convert
96 * @return an int equals to {@code hexDigit}
97 * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
98 */
99 public static int hexDigitMsb0ToInt(final char hexDigit) {
100 switch (hexDigit) {
101 case '0':
102 return 0x0;
103 case '1':
104 return 0x8;
105 case '2':
106 return 0x4;
107 case '3':
108 return 0xC;
109 case '4':
110 return 0x2;
111 case '5':
112 return 0xA;
113 case '6':
114 return 0x6;
115 case '7':
116 return 0xE;
117 case '8':
118 return 0x1;
119 case '9':
120 return 0x9;
121 case 'a':// fall through
122 case 'A':
123 return 0x5;
124 case 'b':// fall through
125 case 'B':
126 return 0xD;
127 case 'c':// fall through
128 case 'C':
129 return 0x3;
130 case 'd':// fall through
131 case 'D':
132 return 0xB;
133 case 'e':// fall through
134 case 'E':
135 return 0x7;
136 case 'f':// fall through
137 case 'F':
138 return 0xF;
139 default:
140 throw new IllegalArgumentException("Cannot interpret '"
141 + hexDigit
142 + "' as a hexadecimal digit");
143 }
144 }
145
146 /**
147 * <p>
148 * Converts a hexadecimal digit into binary (represented as boolean array) using the default
149 * (Lsb0) bit ordering.
150 * </p>
151 * <p>
152 * '1' is converted as follow: (1, 0, 0, 0)
153 * </p>
154 *
155 * @param hexDigit the hexadecimal digit to convert
156 * @return a boolean array with the binary representation of {@code hexDigit}
157 * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
158 */
159 public static boolean[] hexDigitToBinary(final char hexDigit) {
160 switch (hexDigit) {
161 case '0':
162 return new boolean[]{false, false, false, false};
163 case '1':
164 return new boolean[]{true, false, false, false};
165 case '2':
166 return new boolean[]{false, true, false, false};
167 case '3':
168 return new boolean[]{true, true, false, false};
169 case '4':
170 return new boolean[]{false, false, true, false};
171 case '5':
172 return new boolean[]{true, false, true, false};
173 case '6':
174 return new boolean[]{false, true, true, false};
175 case '7':
176 return new boolean[]{true, true, true, false};
177 case '8':
178 return new boolean[]{false, false, false, true};
179 case '9':
180 return new boolean[]{true, false, false, true};
181 case 'a':// fall through
182 case 'A':
183 return new boolean[]{false, true, false, true};
184 case 'b':// fall through
185 case 'B':
186 return new boolean[]{true, true, false, true};
187 case 'c':// fall through
188 case 'C':
189 return new boolean[]{false, false, true, true};
190 case 'd':// fall through
191 case 'D':
192 return new boolean[]{true, false, true, true};
193 case 'e':// fall through
194 case 'E':
195 return new boolean[]{false, true, true, true};
196 case 'f':// fall through
197 case 'F':
198 return new boolean[]{true, true, true, true};
199 default:
200 throw new IllegalArgumentException("Cannot interpret '"
201 + hexDigit
202 + "' as a hexadecimal digit");
203 }
204 }
205
206 /**
207 * <p>
208 * Converts a hexadecimal digit into binary (represented as boolean array) using the Msb0
209 * bit ordering.
210 * </p>
211 * <p>
212 * '1' is converted as follow: (0, 0, 0, 1)
213 * </p>
214 *
215 * @param hexDigit the hexadecimal digit to convert
216 * @return a boolean array with the binary representation of {@code hexDigit}
217 * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
218 */
219 public static boolean[] hexDigitMsb0ToBinary(final char hexDigit) {
220 switch (hexDigit) {
221 case '0':
222 return new boolean[]{false, false, false, false};
223 case '1':
224 return new boolean[]{false, false, false, true};
225 case '2':
226 return new boolean[]{false, false, true, false};
227 case '3':
228 return new boolean[]{false, false, true, true};
229 case '4':
230 return new boolean[]{false, true, false, false};
231 case '5':
232 return new boolean[]{false, true, false, true};
233 case '6':
234 return new boolean[]{false, true, true, false};
235 case '7':
236 return new boolean[]{false, true, true, true};
237 case '8':
238 return new boolean[]{true, false, false, false};
239 case '9':
240 return new boolean[]{true, false, false, true};
241 case 'a':// fall through
242 case 'A':
243 return new boolean[]{true, false, true, false};
244 case 'b':// fall through
245 case 'B':
246 return new boolean[]{true, false, true, true};
247 case 'c':// fall through
248 case 'C':
249 return new boolean[]{true, true, false, false};
250 case 'd':// fall through
251 case 'D':
252 return new boolean[]{true, true, false, true};
253 case 'e':// fall through
254 case 'E':
255 return new boolean[]{true, true, true, false};
256 case 'f':// fall through
257 case 'F':
258 return new boolean[]{true, true, true, true};
259 default:
260 throw new IllegalArgumentException("Cannot interpret '"
261 + hexDigit
262 + "' as a hexadecimal digit");
263 }
264 }
265
266 /**
267 * <p>
268 * Converts binary (represented as boolean array) to a hexadecimal digit using the default
269 * (Lsb0) bit ordering.
270 * </p>
271 * <p>
272 * (1, 0, 0, 0) is converted as follow: '1'
273 * </p>
274 *
275 * @param src the binary to convert
276 * @return a hexadecimal digit representing the selected bits
277 * @throws IllegalArgumentException if {@code src} is empty
278 * @throws NullPointerException if {@code src} is {@code null}
279 */
280 public static char binaryToHexDigit(final boolean[] src) {
281 return binaryToHexDigit(src, 0);
282 }
283
284 /**
285 * <p>
286 * Converts binary (represented as boolean array) to a hexadecimal digit using the default
287 * (Lsb0) bit ordering.
288 * </p>
289 * <p>
290 * (1, 0, 0, 0) is converted as follow: '1'
291 * </p>
292 *
293 * @param src the binary to convert
294 * @param srcPos the position of the lsb to start the conversion
295 * @return a hexadecimal digit representing the selected bits
296 * @throws IllegalArgumentException if {@code src} is empty
297 * @throws NullPointerException if {@code src} is {@code null}
298 */
299 public static char binaryToHexDigit(final boolean[] src, final int srcPos) {
300 if (src.length == 0) {
301 throw new IllegalArgumentException("Cannot convert an empty array.");
302 }
303 if (src.length > srcPos + 3 && src[srcPos + 3]) {
304 if (src.length > srcPos + 2 && src[srcPos + 2]) {
305 if (src.length > srcPos + 1 && src[srcPos + 1]) {
306 if (src[srcPos]) {
307 return 'f';
308 } else {
309 return 'e';
310 }
311 } else {
312 if (src[srcPos]) {
313 return 'd';
314 } else {
315 return 'c';
316 }
317 }
318 } else {
319 if (src.length > srcPos + 1 && src[srcPos + 1]) {
320 if (src[srcPos]) {
321 return 'b';
322 } else {
323 return 'a';
324 }
325 } else {
326 if (src[srcPos]) {
327 return '9';
328 } else {
329 return '8';
330 }
331 }
332 }
333 } else {
334 if (src.length > srcPos + 2 && src[srcPos + 2]) {
335 if (src.length > srcPos + 1 && src[srcPos + 1]) {
336 if (src[srcPos]) {
337 return '7';
338 } else {
339 return '6';
340 }
341 } else {
342 if (src[srcPos]) {
343 return '5';
344 } else {
345 return '4';
346 }
347 }
348 } else {
349 if (src.length > srcPos + 1 && src[srcPos + 1]) {
350 if (src[srcPos]) {
351 return '3';
352 } else {
353 return '2';
354 }
355 } else {
356 if (src[srcPos]) {
357 return '1';
358 } else {
359 return '0';
360 }
361 }
362 }
363 }
364 }
365
366 /**
367 * <p>
368 * Converts binary (represented as boolean array) to a hexadecimal digit using the Msb0 bit
369 * ordering.
370 * </p>
371 * <p>
372 * (1, 0, 0, 0) is converted as follow: '8'
373 * </p>
374 *
375 * @param src the binary to convert
376 * @return a hexadecimal digit representing the selected bits
377 * @throws IllegalArgumentException if {@code src} is empty, {@code src.length < 4} or
378 * {@code src.length > 8}
379 * @throws NullPointerException if {@code src} is {@code null}
380 */
381 public static char binaryToHexDigitMsb0_4bits(final boolean[] src) {
382 return binaryToHexDigitMsb0_4bits(src, 0);
383 }
384
385 /**
386 * <p>
387 * Converts binary (represented as boolean array) to a hexadecimal digit using the Msb0 bit
388 * ordering.
389 * </p>
390 * <p>
391 * (1, 0, 0, 0) is converted as follow: '8' (1,0,0,1,1,0,1,0) with srcPos = 3 is converted
392 * to 'D'
393 * </p>
394 *
395 * @param src the binary to convert
396 * @param srcPos the position of the lsb to start the conversion
397 * @return a hexadecimal digit representing the selected bits
398 * @throws IllegalArgumentException if {@code src} is empty, {@code src.length > 8} or
399 * {@code src.length - srcPos < 4}
400 * @throws NullPointerException if {@code src} is {@code null}
401 */
402 public static char binaryToHexDigitMsb0_4bits(final boolean[] src, final int srcPos) {
403 if (src.length > 8) {
404 throw new IllegalArgumentException("src.length>8: src.length=" + src.length);
405 }
406 if (src.length - srcPos < 4) {
407 throw new IllegalArgumentException("src.length-srcPos<4: src.length="
408 + src.length
409 + ", srcPos="
410 + srcPos);
411 }
412 if (src[srcPos + 3]) {
413 if (src[srcPos + 2]) {
414 if (src[srcPos + 1]) {
415 if (src[srcPos]) {
416 return 'f';
417 } else {
418 return '7';
419 }
420 } else {
421 if (src[srcPos]) {
422 return 'b';
423 } else {
424 return '3';
425 }
426 }
427 } else {
428 if (src[srcPos + 1]) {
429 if (src[srcPos]) {
430 return 'd';
431 } else {
432 return '5';
433 }
434 } else {
435 if (src[srcPos]) {
436 return '9';
437 } else {
438 return '1';
439 }
440 }
441 }
442 } else {
443 if (src[srcPos + 2]) {
444 if (src[srcPos + 1]) {
445 if (src[srcPos]) {
446 return 'e';
447 } else {
448 return '6';
449 }
450 } else {
451 if (src[srcPos]) {
452 return 'a';
453 } else {
454 return '2';
455 }
456 }
457 } else {
458 if (src[srcPos + 1]) {
459 if (src[srcPos]) {
460 return 'c';
461 } else {
462 return '4';
463 }
464 } else {
465 if (src[srcPos]) {
466 return '8';
467 } else {
468 return '0';
469 }
470 }
471 }
472 }
473 }
474
475 /**
476 * <p>
477 * Converts the first 4 bits of a binary (represented as boolean array) in big endian Msb0
478 * bit ordering to a hexadecimal digit.
479 * </p>
480 * <p>
481 * (1, 0, 0, 0) is converted as follow: '8' (1,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0) is converted
482 * to '4'
483 * </p>
484 *
485 * @param src the binary to convert
486 * @return a hexadecimal digit representing the selected bits
487 * @throws IllegalArgumentException if {@code src} is empty
488 * @throws NullPointerException if {@code src} is {@code null}
489 */
490 public static char binaryBeMsb0ToHexDigit(final boolean[] src) {
491 return binaryBeMsb0ToHexDigit(src, 0);
492 }
493
494 /**
495 * <p>
496 * Converts a binary (represented as boolean array) in big endian Msb0 bit ordering to a
497 * hexadecimal digit.
498 * </p>
499 * <p>
500 * (1, 0, 0, 0) with srcPos = 0 is converted as follow: '8' (1,0,0,0,0,0,0,0,
501 * 0,0,0,1,0,1,0,0) with srcPos = 2 is converted to '5'
502 * </p>
503 *
504 * @param src the binary to convert
505 * @param srcPos the position of the lsb to start the conversion
506 * @return a hexadecimal digit representing the selected bits
507 * @throws IllegalArgumentException if {@code src} is empty
508 * @throws NullPointerException if {@code src} is {@code null}
509 */
510 public static char binaryBeMsb0ToHexDigit(boolean[] src, int srcPos) {
511 if (src.length == 0) {
512 throw new IllegalArgumentException("Cannot convert an empty array.");
513 }
514 final int beSrcPos = src.length - 1 - srcPos;
515 final int srcLen = Math.min(4, beSrcPos + 1);
516 final boolean[] paddedSrc = new boolean[4];
517 System.arraycopy(src, beSrcPos + 1 - srcLen, paddedSrc, 4 - srcLen, srcLen);
518 src = paddedSrc;
519 srcPos = 0;
520 if (src[srcPos]) {
521 if (src.length > srcPos + 1 && src[srcPos + 1]) {
522 if (src.length > srcPos + 2 && src[srcPos + 2]) {
523 if (src.length > srcPos + 3 && src[srcPos + 3]) {
524 return 'f';
525 } else {
526 return 'e';
527 }
528 } else {
529 if (src.length > srcPos + 3 && src[srcPos + 3]) {
530 return 'd';
531 } else {
532 return 'c';
533 }
534 }
535 } else {
536 if (src.length > srcPos + 2 && src[srcPos + 2]) {
537 if (src.length > srcPos + 3 && src[srcPos + 3]) {
538 return 'b';
539 } else {
540 return 'a';
541 }
542 } else {
543 if (src.length > srcPos + 3 && src[srcPos + 3]) {
544 return '9';
545 } else {
546 return '8';
547 }
548 }
549 }
550 } else {
551 if (src.length > srcPos + 1 && src[srcPos + 1]) {
552 if (src.length > srcPos + 2 && src[srcPos + 2]) {
553 if (src.length > srcPos + 3 && src[srcPos + 3]) {
554 return '7';
555 } else {
556 return '6';
557 }
558 } else {
559 if (src.length > srcPos + 3 && src[srcPos + 3]) {
560 return '5';
561 } else {
562 return '4';
563 }
564 }
565 } else {
566 if (src.length > srcPos + 2 && src[srcPos + 2]) {
567 if (src.length > srcPos + 3 && src[srcPos + 3]) {
568 return '3';
569 } else {
570 return '2';
571 }
572 } else {
573 if (src.length > srcPos + 3 && src[srcPos + 3]) {
574 return '1';
575 } else {
576 return '0';
577 }
578 }
579 }
580 }
581 }
582
583 /**
584 * <p>
585 * Converts the 4 lsb of an int to a hexadecimal digit.
586 * </p>
587 * <p>
588 * 0 returns '0'
589 * </p>
590 * <p>
591 * 1 returns '1'
592 * </p>
593 * <p>
594 * 10 returns 'A' and so on...
595 * </p>
596 *
597 * @param nibble the 4 bits to convert
598 * @return a hexadecimal digit representing the 4 lsb of {@code nibble}
599 * @throws IllegalArgumentException if {@code nibble < 0} or {@code nibble > 15}
600 */
601 public static char intToHexDigit(final int nibble) {
602 final char c = Character.forDigit(nibble, 16);
603 if (c == Character.MIN_VALUE) {
604 throw new IllegalArgumentException("nibble value not between 0 and 15: " + nibble);
605 }
606 return c;
607 }
608
609 /**
610 * <p>
611 * Converts the 4 lsb of an int to a hexadecimal digit encoded using the Msb0 bit ordering.
612 * </p>
613 * <p>
614 * 0 returns '0'
615 * </p>
616 * <p>
617 * 1 returns '8'
618 * </p>
619 * <p>
620 * 10 returns '5' and so on...
621 * </p>
622 *
623 * @param nibble the 4 bits to convert
624 * @return a hexadecimal digit representing the 4 lsb of {@code nibble}
625 * @throws IllegalArgumentException if {@code nibble < 0} or {@code nibble > 15}
626 */
627 public static char intToHexDigitMsb0(final int nibble) {
628 switch (nibble) {
629 case 0x0:
630 return '0';
631 case 0x1:
632 return '8';
633 case 0x2:
634 return '4';
635 case 0x3:
636 return 'c';
637 case 0x4:
638 return '2';
639 case 0x5:
640 return 'a';
641 case 0x6:
642 return '6';
643 case 0x7:
644 return 'e';
645 case 0x8:
646 return '1';
647 case 0x9:
648 return '9';
649 case 0xA:
650 return '5';
651 case 0xB:
652 return 'd';
653 case 0xC:
654 return '3';
655 case 0xD:
656 return 'b';
657 case 0xE:
658 return '7';
659 case 0xF:
660 return 'f';
661 default:
662 throw new IllegalArgumentException("nibble value not between 0 and 15: " + nibble);
663 }
664 }
665
666 /**
667 * <p>
668 * Converts an array of int into a long using the default (little endian, Lsb0) byte and bit
669 * ordering.
670 * </p>
671 *
672 * @param src the int array to convert
673 * @param srcPos the position in {@code src}, in int unit, from where to start the
674 * conversion
675 * @param dstInit initial value of the destination long
676 * @param dstPos the position of the lsb, in bits, in the result long
677 * @param nInts the number of ints to convert
678 * @return a long containing the selected bits
679 * @throws IllegalArgumentException if {@code (nInts-1)*32+dstPos >= 64}
680 * @throws NullPointerException if {@code src} is {@code null}
681 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nInts > src.length}
682 */
683 public static long intArrayToLong(final int[] src, final int srcPos, final long dstInit, final int dstPos, final int nInts) {
684 if ((src.length == 0 && srcPos == 0) || 0 == nInts) {
685 return dstInit;
686 }
687 if ((nInts - 1) * 32 + dstPos >= 64) {
688 throw new IllegalArgumentException(
689 "(nInts-1)*32+dstPos is greather or equal to than 64");
690 }
691 long out = dstInit;
692 int shift = 0;
693 for (int i = 0; i < nInts; i++ ) {
694 shift = i * 32 + dstPos;
695 final long bits = ((0xffffffffL & src[i + srcPos]) << shift);
696 final long mask = 0xffffffffL << shift;
697 out = (out & ~mask) | bits;
698 }
699 return out;
700 }
701
702 /**
703 * <p>
704 * Converts an array of short into a long using the default (little endian, Lsb0) byte and
705 * bit ordering.
706 * </p>
707 *
708 * @param src the short array to convert
709 * @param srcPos the position in {@code src}, in short unit, from where to start the
710 * conversion
711 * @param dstInit initial value of the destination long
712 * @param dstPos the position of the lsb, in bits, in the result long
713 * @param nShorts the number of shorts to convert
714 * @return a long containing the selected bits
715 * @throws NullPointerException if {@code src} is {@code null}
716 * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 64}
717 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nShorts > src.length}
718 */
719 public static long shortArrayToLong(final short[] src, final int srcPos, final long dstInit, final int dstPos,
720 final int nShorts) {
721 if ((src.length == 0 && srcPos == 0) || 0 == nShorts) {
722 return dstInit;
723 }
724 if ((nShorts - 1) * 16 + dstPos >= 64) {
725 throw new IllegalArgumentException(
726 "(nShorts-1)*16+dstPos is greather or equal to than 64");
727 }
728 long out = dstInit;
729 int shift = 0;
730 for (int i = 0; i < nShorts; i++ ) {
731 shift = i * 16 + dstPos;
732 final long bits = (0xffffL & src[i + srcPos]) << shift;
733 final long mask = 0xffffL << shift;
734 out = (out & ~mask) | bits;
735 }
736 return out;
737 }
738
739 /**
740 * <p>
741 * Converts an array of short into a int using the default (little endian, Lsb0) byte and
742 * bit ordering.
743 * </p>
744 *
745 * @param src the short array to convert
746 * @param srcPos the position in {@code src}, in short unit, from where to start the
747 * conversion
748 * @param dstInit initial value of the destination int
749 * @param dstPos the position of the lsb, in bits, in the result int
750 * @param nShorts the number of shorts to convert
751 * @return a int containing the selected bits
752 * @throws NullPointerException if {@code src} is {@code null}
753 * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 32}
754 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nShorts > src.length}
755 */
756 public static int shortArrayToInt(final short[] src, final int srcPos, final int dstInit, final int dstPos,
757 final int nShorts) {
758 if ((src.length == 0 && srcPos == 0) || 0 == nShorts) {
759 return dstInit;
760 }
761 if ((nShorts - 1) * 16 + dstPos >= 32) {
762 throw new IllegalArgumentException(
763 "(nShorts-1)*16+dstPos is greather or equal to than 32");
764 }
765 int out = dstInit;
766 int shift = 0;
767 for (int i = 0; i < nShorts; i++ ) {
768 shift = i * 16 + dstPos;
769 final int bits = (0xffff & src[i + srcPos]) << shift;
770 final int mask = 0xffff << shift;
771 out = (out & ~mask) | bits;
772 }
773 return out;
774 }
775
776 /**
777 * <p>
778 * Converts an array of byte into a long using the default (little endian, Lsb0) byte and
779 * bit ordering.
780 * </p>
781 *
782 * @param src the byte array to convert
783 * @param srcPos the position in {@code src}, in byte unit, from where to start the
784 * conversion
785 * @param dstInit initial value of the destination long
786 * @param dstPos the position of the lsb, in bits, in the result long
787 * @param nBytes the number of bytes to convert
788 * @return a long containing the selected bits
789 * @throws NullPointerException if {@code src} is {@code null}
790 * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 64}
791 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBytes > src.length}
792 */
793 public static long byteArrayToLong(final byte[] src, final int srcPos, final long dstInit, final int dstPos,
794 final int nBytes) {
795 if ((src.length == 0 && srcPos == 0) || 0 == nBytes) {
796 return dstInit;
797 }
798 if ((nBytes - 1) * 8 + dstPos >= 64) {
799 throw new IllegalArgumentException(
800 "(nBytes-1)*8+dstPos is greather or equal to than 64");
801 }
802 long out = dstInit;
803 int shift = 0;
804 for (int i = 0; i < nBytes; i++ ) {
805 shift = i * 8 + dstPos;
806 final long bits = (0xffL & src[i + srcPos]) << shift;
807 final long mask = 0xffL << shift;
808 out = (out & ~mask) | bits;
809 }
810 return out;
811 }
812
813 /**
814 * <p>
815 * Converts an array of byte into a int using the default (little endian, Lsb0) byte and bit
816 * ordering.
817 * </p>
818 *
819 * @param src the byte array to convert
820 * @param srcPos the position in {@code src}, in byte unit, from where to start the
821 * conversion
822 * @param dstInit initial value of the destination int
823 * @param dstPos the position of the lsb, in bits, in the result int
824 * @param nBytes the number of bytes to convert
825 * @return a int containing the selected bits
826 * @throws NullPointerException if {@code src} is {@code null}
827 * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 32}
828 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBytes > src.length}
829 */
830 public static int byteArrayToInt(final byte[] src, final int srcPos, final int dstInit, final int dstPos, final int nBytes) {
831 if ((src.length == 0 && srcPos == 0) || 0 == nBytes) {
832 return dstInit;
833 }
834 if ((nBytes - 1) * 8 + dstPos >= 32) {
835 throw new IllegalArgumentException(
836 "(nBytes-1)*8+dstPos is greather or equal to than 32");
837 }
838 int out = dstInit;
839 int shift = 0;
840 for (int i = 0; i < nBytes; i++ ) {
841 shift = i * 8 + dstPos;
842 final int bits = (0xff & src[i + srcPos]) << shift;
843 final int mask = 0xff << shift;
844 out = (out & ~mask) | bits;
845 }
846 return out;
847 }
848
849 /**
850 * <p>
851 * Converts an array of byte into a short using the default (little endian, Lsb0) byte and
852 * bit ordering.
853 * </p>
854 *
855 * @param src the byte array to convert
856 * @param srcPos the position in {@code src}, in byte unit, from where to start the
857 * conversion
858 * @param dstInit initial value of the destination short
859 * @param dstPos the position of the lsb, in bits, in the result short
860 * @param nBytes the number of bytes to convert
861 * @return a short containing the selected bits
862 * @throws NullPointerException if {@code src} is {@code null}
863 * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 16}
864 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBytes > src.length}
865 */
866 public static short byteArrayToShort(final byte[] src, final int srcPos, final short dstInit, final int dstPos,
867 final int nBytes) {
868 if ((src.length == 0 && srcPos == 0) || 0 == nBytes) {
869 return dstInit;
870 }
871 if ((nBytes - 1) * 8 + dstPos >= 16) {
872 throw new IllegalArgumentException(
873 "(nBytes-1)*8+dstPos is greather or equal to than 16");
874 }
875 short out = dstInit;
876 int shift = 0;
877 for (int i = 0; i < nBytes; i++ ) {
878 shift = i * 8 + dstPos;
879 final int bits = (0xff & src[i + srcPos]) << shift;
880 final int mask = 0xff << shift;
881 out = (short)((out & ~mask) | bits);
882 }
883 return out;
884 }
885
886 /**
887 * <p>
888 * Converts an array of Char into a long using the default (little endian, Lsb0) byte and
889 * bit ordering.
890 * </p>
891 *
892 * @param src the hex string to convert
893 * @param srcPos the position in {@code src}, in Char unit, from where to start the
894 * conversion
895 * @param dstInit initial value of the destination long
896 * @param dstPos the position of the lsb, in bits, in the result long
897 * @param nHex the number of Chars to convert
898 * @return a long containing the selected bits
899 * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 64}
900 */
901 public static long hexToLong(final String src, final int srcPos, final long dstInit, final int dstPos, final int nHex) {
902 if (0 == nHex) {
903 return dstInit;
904 }
905 if ((nHex - 1) * 4 + dstPos >= 64) {
906 throw new IllegalArgumentException(
907 "(nHexs-1)*4+dstPos is greather or equal to than 64");
908 }
909 long out = dstInit;
910 int shift = 0;
911 for (int i = 0; i < nHex; i++ ) {
912 shift = i * 4 + dstPos;
913 final long bits = (0xfL & hexDigitToInt(src.charAt(i + srcPos))) << shift;
914 final long mask = 0xfL << shift;
915 out = (out & ~mask) | bits;
916 }
917 return out;
918 }
919
920 /**
921 * <p>
922 * Converts an array of Char into a int using the default (little endian, Lsb0) byte and bit
923 * ordering.
924 * </p>
925 *
926 * @param src the hex string to convert
927 * @param srcPos the position in {@code src}, in Char unit, from where to start the
928 * conversion
929 * @param dstInit initial value of the destination int
930 * @param dstPos the position of the lsb, in bits, in the result int
931 * @param nHex the number of Chars to convert
932 * @return a int containing the selected bits
933 * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 32}
934 */
935 public static int hexToInt(final String src, final int srcPos, final int dstInit, final int dstPos, final int nHex) {
936 if (0 == nHex) {
937 return dstInit;
938 }
939 if ((nHex - 1) * 4 + dstPos >= 32) {
940 throw new IllegalArgumentException(
941 "(nHexs-1)*4+dstPos is greather or equal to than 32");
942 }
943 int out = dstInit;
944 int shift = 0;
945 for (int i = 0; i < nHex; i++ ) {
946 shift = i * 4 + dstPos;
947 final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift;
948 final int mask = 0xf << shift;
949 out = (out & ~mask) | bits;
950 }
951 return out;
952 }
953
954 /**
955 * <p>
956 * Converts an array of Char into a short using the default (little endian, Lsb0) byte and
957 * bit ordering.
958 * </p>
959 *
960 * @param src the hex string to convert
961 * @param srcPos the position in {@code src}, in Char unit, from where to start the
962 * conversion
963 * @param dstInit initial value of the destination short
964 * @param dstPos the position of the lsb, in bits, in the result short
965 * @param nHex the number of Chars to convert
966 * @return a short containing the selected bits
967 * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 16}
968 */
969 public static short hexToShort(final String src, final int srcPos, final short dstInit, final int dstPos, final int nHex) {
970 if (0 == nHex) {
971 return dstInit;
972 }
973 if ((nHex - 1) * 4 + dstPos >= 16) {
974 throw new IllegalArgumentException(
975 "(nHexs-1)*4+dstPos is greather or equal to than 16");
976 }
977 short out = dstInit;
978 int shift = 0;
979 for (int i = 0; i < nHex; i++ ) {
980 shift = i * 4 + dstPos;
981 final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift;
982 final int mask = 0xf << shift;
983 out = (short)((out & ~mask) | bits);
984 }
985 return out;
986 }
987
988 /**
989 * <p>
990 * Converts an array of Char into a byte using the default (little endian, Lsb0) byte and
991 * bit ordering.
992 * </p>
993 *
994 * @param src the hex string to convert
995 * @param srcPos the position in {@code src}, in Char unit, from where to start the
996 * conversion
997 * @param dstInit initial value of the destination byte
998 * @param dstPos the position of the lsb, in bits, in the result byte
999 * @param nHex the number of Chars to convert
1000 * @return a byte containing the selected bits
1001 * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 8}
1002 */
1003 public static byte hexToByte(final String src, final int srcPos, final byte dstInit, final int dstPos, final int nHex) {
1004 if (0 == nHex) {
1005 return dstInit;
1006 }
1007 if ((nHex - 1) * 4 + dstPos >= 8) {
1008 throw new IllegalArgumentException(
1009 "(nHexs-1)*4+dstPos is greather or equal to than 8");
1010 }
1011 byte out = dstInit;
1012 int shift = 0;
1013 for (int i = 0; i < nHex; i++ ) {
1014 shift = i * 4 + dstPos;
1015 final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift;
1016 final int mask = 0xf << shift;
1017 out = (byte)((out & ~mask) | bits);
1018 }
1019 return out;
1020 }
1021
1022 /**
1023 * <p>
1024 * Converts binary (represented as boolean array) into a long using the default (little
1025 * endian, Lsb0) byte and bit ordering.
1026 * </p>
1027 *
1028 * @param src the binary to convert
1029 * @param srcPos the position in {@code src}, in boolean unit, from where to start the
1030 * conversion
1031 * @param dstInit initial value of the destination long
1032 * @param dstPos the position of the lsb, in bits, in the result long
1033 * @param nBools the number of booleans to convert
1034 * @return a long containing the selected bits
1035 * @throws NullPointerException if {@code src} is {@code null}
1036 * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 64}
1037 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
1038 */
1039 public static long binaryToLong(final boolean[] src, final int srcPos, final long dstInit, final int dstPos,
1040 final int nBools) {
1041 if ((src.length == 0 && srcPos == 0) || 0 == nBools) {
1042 return dstInit;
1043 }
1044 if (nBools - 1 + dstPos >= 64) {
1045 throw new IllegalArgumentException(
1046 "nBools-1+dstPos is greather or equal to than 64");
1047 }
1048 long out = dstInit;
1049 int shift = 0;
1050 for (int i = 0; i < nBools; i++ ) {
1051 shift = i * 1 + dstPos;
1052 final long bits = (src[i + srcPos] ? 1L : 0) << shift;
1053 final long mask = 0x1L << shift;
1054 out = (out & ~mask) | bits;
1055 }
1056 return out;
1057 }
1058
1059 /**
1060 * <p>
1061 * Converts binary (represented as boolean array) into a int using the default (little
1062 * endian, Lsb0) byte and bit ordering.
1063 * </p>
1064 *
1065 * @param src the binary to convert
1066 * @param srcPos the position in {@code src}, in boolean unit, from where to start the
1067 * conversion
1068 * @param dstInit initial value of the destination int
1069 * @param dstPos the position of the lsb, in bits, in the result int
1070 * @param nBools the number of booleans to convert
1071 * @return a int containing the selected bits
1072 * @throws NullPointerException if {@code src} is {@code null}
1073 * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 32}
1074 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
1075 */
1076 public static int binaryToInt(final boolean[] src, final int srcPos, final int dstInit, final int dstPos, final int nBools) {
1077 if ((src.length == 0 && srcPos == 0) || 0 == nBools) {
1078 return dstInit;
1079 }
1080 if (nBools - 1 + dstPos >= 32) {
1081 throw new IllegalArgumentException(
1082 "nBools-1+dstPos is greather or equal to than 32");
1083 }
1084 int out = dstInit;
1085 int shift = 0;
1086 for (int i = 0; i < nBools; i++ ) {
1087 shift = i * 1 + dstPos;
1088 final int bits = (src[i + srcPos] ? 1 : 0) << shift;
1089 final int mask = 0x1 << shift;
1090 out = (out & ~mask) | bits;
1091 }
1092 return out;
1093 }
1094
1095 /**
1096 * <p>
1097 * Converts binary (represented as boolean array) into a short using the default (little
1098 * endian, Lsb0) byte and bit ordering.
1099 * </p>
1100 *
1101 * @param src the binary to convert
1102 * @param srcPos the position in {@code src}, in boolean unit, from where to start the
1103 * conversion
1104 * @param dstInit initial value of the destination short
1105 * @param dstPos the position of the lsb, in bits, in the result short
1106 * @param nBools the number of booleans to convert
1107 * @return a short containing the selected bits
1108 * @throws NullPointerException if {@code src} is {@code null}
1109 * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 16}
1110 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
1111 */
1112 public static short binaryToShort(final boolean[] src, final int srcPos, final short dstInit, final int dstPos,
1113 final int nBools) {
1114 if ((src.length == 0 && srcPos == 0) || 0 == nBools) {
1115 return dstInit;
1116 }
1117 if (nBools - 1 + dstPos >= 16) {
1118 throw new IllegalArgumentException(
1119 "nBools-1+dstPos is greather or equal to than 16");
1120 }
1121 short out = dstInit;
1122 int shift = 0;
1123 for (int i = 0; i < nBools; i++ ) {
1124 shift = i * 1 + dstPos;
1125 final int bits = (src[i + srcPos] ? 1 : 0) << shift;
1126 final int mask = 0x1 << shift;
1127 out = (short)((out & ~mask) | bits);
1128 }
1129 return out;
1130 }
1131
1132 /**
1133 * <p>
1134 * Converts binary (represented as boolean array) into a byte using the default (little
1135 * endian, Lsb0) byte and bit ordering.
1136 * </p>
1137 *
1138 * @param src the binary to convert
1139 * @param srcPos the position in {@code src}, in boolean unit, from where to start the
1140 * conversion
1141 * @param dstInit initial value of the destination byte
1142 * @param dstPos the position of the lsb, in bits, in the result byte
1143 * @param nBools the number of booleans to convert
1144 * @return a byte containing the selected bits
1145 * @throws NullPointerException if {@code src} is {@code null}
1146 * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 8}
1147 * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
1148 */
1149 public static byte binaryToByte(final boolean[] src, final int srcPos, final byte dstInit, final int dstPos,
1150 final int nBools) {
1151 if ((src.length == 0 && srcPos == 0) || 0 == nBools) {
1152 return dstInit;
1153 }
1154 if (nBools - 1 + dstPos >= 8) {
1155 throw new IllegalArgumentException("nBools-1+dstPos is greather or equal to than 8");
1156 }
1157 byte out = dstInit;
1158 int shift = 0;
1159 for (int i = 0; i < nBools; i++ ) {
1160 shift = i * 1 + dstPos;
1161 final int bits = (src[i + srcPos] ? 1 : 0) << shift;
1162 final int mask = 0x1 << shift;
1163 out = (byte)((out & ~mask) | bits);
1164 }
1165 return out;
1166 }
1167
1168 /**
1169 * <p>
1170 * Converts a long into an array of int using the default (little endian, Lsb0) byte and bit
1171 * ordering.
1172 * </p>
1173 *
1174 * @param src the long to convert
1175 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1176 * @param dst the destination array
1177 * @param dstPos the position in {@code dst} where to copy the result
1178 * @param nInts the number of ints to copy to {@code dst}, must be smaller or equal to the
1179 * width of the input (from srcPos to msb)
1180 * @return {@code dst}
1181 * @throws NullPointerException if {@code dst} is {@code null} and {@code nInts > 0}
1182 * @throws IllegalArgumentException if {@code (nInts-1)*32+srcPos >= 64}
1183 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nInts > dst.length}
1184 */
1185 public static int[] longToIntArray(final long src, final int srcPos, final int[] dst, final int dstPos, final int nInts) {
1186 if (0 == nInts) {
1187 return dst;
1188 }
1189 if ((nInts - 1) * 32 + srcPos >= 64) {
1190 throw new IllegalArgumentException(
1191 "(nInts-1)*32+srcPos is greather or equal to than 64");
1192 }
1193 int shift = 0;
1194 for (int i = 0; i < nInts; i++ ) {
1195 shift = i * 32 + srcPos;
1196 dst[dstPos + i] = (int)(0xffffffff & (src >> shift));
1197 }
1198 return dst;
1199 }
1200
1201 /**
1202 * <p>
1203 * Converts a long into an array of short using the default (little endian, Lsb0) byte and
1204 * bit ordering.
1205 * </p>
1206 *
1207 * @param src the long to convert
1208 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1209 * @param dst the destination array
1210 * @param dstPos the position in {@code dst} where to copy the result
1211 * @param nShorts the number of shorts to copy to {@code dst}, must be smaller or equal to
1212 * the width of the input (from srcPos to msb)
1213 * @return {@code dst}
1214 * @throws NullPointerException if {@code dst} is {@code null}
1215 * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 64}
1216 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nShorts > dst.length}
1217 */
1218 public static short[] longToShortArray(final long src, final int srcPos, final short[] dst, final int dstPos,
1219 final int nShorts) {
1220 if (0 == nShorts) {
1221 return dst;
1222 }
1223 if ((nShorts - 1) * 16 + srcPos >= 64) {
1224 throw new IllegalArgumentException(
1225 "(nShorts-1)*16+srcPos is greather or equal to than 64");
1226 }
1227 int shift = 0;
1228 for (int i = 0; i < nShorts; i++ ) {
1229 shift = i * 16 + srcPos;
1230 dst[dstPos + i] = (short)(0xffff & (src >> shift));
1231 }
1232 return dst;
1233 }
1234
1235 /**
1236 * <p>
1237 * Converts a int into an array of short using the default (little endian, Lsb0) byte and
1238 * bit ordering.
1239 * </p>
1240 *
1241 * @param src the int to convert
1242 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1243 * @param dst the destination array
1244 * @param dstPos the position in {@code dst} where to copy the result
1245 * @param nShorts the number of shorts to copy to {@code dst}, must be smaller or equal to
1246 * the width of the input (from srcPos to msb)
1247 * @return {@code dst}
1248 * @throws NullPointerException if {@code dst} is {@code null}
1249 * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 32}
1250 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nShorts > dst.length}
1251 */
1252 public static short[] intToShortArray(final int src, final int srcPos, final short[] dst, final int dstPos,
1253 final int nShorts) {
1254 if (0 == nShorts) {
1255 return dst;
1256 }
1257 if ((nShorts - 1) * 16 + srcPos >= 32) {
1258 throw new IllegalArgumentException(
1259 "(nShorts-1)*16+srcPos is greather or equal to than 32");
1260 }
1261 int shift = 0;
1262 for (int i = 0; i < nShorts; i++ ) {
1263 shift = i * 16 + srcPos;
1264 dst[dstPos + i] = (short)(0xffff & (src >> shift));
1265 }
1266 return dst;
1267 }
1268
1269 /**
1270 * <p>
1271 * Converts a long into an array of byte using the default (little endian, Lsb0) byte and
1272 * bit ordering.
1273 * </p>
1274 *
1275 * @param src the long to convert
1276 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1277 * @param dst the destination array
1278 * @param dstPos the position in {@code dst} where to copy the result
1279 * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
1280 * width of the input (from srcPos to msb)
1281 * @return {@code dst}
1282 * @throws NullPointerException if {@code dst} is {@code null}
1283 * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 64}
1284 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
1285 */
1286 public static byte[] longToByteArray(final long src, final int srcPos, final byte[] dst, final int dstPos,
1287 final int nBytes) {
1288 if (0 == nBytes) {
1289 return dst;
1290 }
1291 if ((nBytes - 1) * 8 + srcPos >= 64) {
1292 throw new IllegalArgumentException(
1293 "(nBytes-1)*8+srcPos is greather or equal to than 64");
1294 }
1295 int shift = 0;
1296 for (int i = 0; i < nBytes; i++ ) {
1297 shift = i * 8 + srcPos;
1298 dst[dstPos + i] = (byte)(0xff & (src >> shift));
1299 }
1300 return dst;
1301 }
1302
1303 /**
1304 * <p>
1305 * Converts a int into an array of byte using the default (little endian, Lsb0) byte and bit
1306 * ordering.
1307 * </p>
1308 *
1309 * @param src the int to convert
1310 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1311 * @param dst the destination array
1312 * @param dstPos the position in {@code dst} where to copy the result
1313 * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
1314 * width of the input (from srcPos to msb)
1315 * @return {@code dst}
1316 * @throws NullPointerException if {@code dst} is {@code null}
1317 * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 32}
1318 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
1319 */
1320 public static byte[] intToByteArray(final int src, final int srcPos, final byte[] dst, final int dstPos, final int nBytes) {
1321 if (0 == nBytes) {
1322 return dst;
1323 }
1324 if ((nBytes - 1) * 8 + srcPos >= 32) {
1325 throw new IllegalArgumentException(
1326 "(nBytes-1)*8+srcPos is greather or equal to than 32");
1327 }
1328 int shift = 0;
1329 for (int i = 0; i < nBytes; i++ ) {
1330 shift = i * 8 + srcPos;
1331 dst[dstPos + i] = (byte)(0xff & (src >> shift));
1332 }
1333 return dst;
1334 }
1335
1336 /**
1337 * <p>
1338 * Converts a short into an array of byte using the default (little endian, Lsb0) byte and
1339 * bit ordering.
1340 * </p>
1341 *
1342 * @param src the short to convert
1343 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1344 * @param dst the destination array
1345 * @param dstPos the position in {@code dst} where to copy the result
1346 * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
1347 * width of the input (from srcPos to msb)
1348 * @return {@code dst}
1349 * @throws NullPointerException if {@code dst} is {@code null}
1350 * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 16}
1351 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
1352 */
1353 public static byte[] shortToByteArray(final short src, final int srcPos, final byte[] dst, final int dstPos,
1354 final int nBytes) {
1355 if (0 == nBytes) {
1356 return dst;
1357 }
1358 if ((nBytes - 1) * 8 + srcPos >= 16) {
1359 throw new IllegalArgumentException(
1360 "(nBytes-1)*8+srcPos is greather or equal to than 16");
1361 }
1362 int shift = 0;
1363 for (int i = 0; i < nBytes; i++ ) {
1364 shift = i * 8 + srcPos;
1365 dst[dstPos + i] = (byte)(0xff & (src >> shift));
1366 }
1367 return dst;
1368 }
1369
1370 /**
1371 * <p>
1372 * Converts a long into an array of Char using the default (little endian, Lsb0) byte and
1373 * bit ordering.
1374 * </p>
1375 *
1376 * @param src the long to convert
1377 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1378 * @param dstInit the initial value for the result String
1379 * @param dstPos the position in {@code dst} where to copy the result
1380 * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
1381 * width of the input (from srcPos to msb)
1382 * @return {@code dst}
1383 * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 64}
1384 * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
1385 */
1386 public static String longToHex(final long src, final int srcPos, final String dstInit, final int dstPos, final int nHexs) {
1387 if (0 == nHexs) {
1388 return dstInit;
1389 }
1390 if ((nHexs - 1) * 4 + srcPos >= 64) {
1391 throw new IllegalArgumentException(
1392 "(nHexs-1)*4+srcPos is greather or equal to than 64");
1393 }
1394 final StringBuilder sb = new StringBuilder(dstInit);
1395 int shift = 0;
1396 int append = sb.length();
1397 for (int i = 0; i < nHexs; i++ ) {
1398 shift = i * 4 + srcPos;
1399 final int bits = (int)(0xF & (src >> shift));
1400 if (dstPos + i == append) {
1401 ++append;
1402 sb.append(intToHexDigit(bits));
1403 } else {
1404 sb.setCharAt(dstPos + i, intToHexDigit(bits));
1405 }
1406 }
1407 return sb.toString();
1408 }
1409
1410 /**
1411 * <p>
1412 * Converts a int into an array of Char using the default (little endian, Lsb0) byte and bit
1413 * ordering.
1414 * </p>
1415 *
1416 * @param src the int to convert
1417 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1418 * @param dstInit the initial value for the result String
1419 * @param dstPos the position in {@code dst} where to copy the result
1420 * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
1421 * width of the input (from srcPos to msb)
1422 * @return {@code dst}
1423 * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 32}
1424 * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
1425 */
1426 public static String intToHex(final int src, final int srcPos, final String dstInit, final int dstPos, final int nHexs) {
1427 if (0 == nHexs) {
1428 return dstInit;
1429 }
1430 if ((nHexs - 1) * 4 + srcPos >= 32) {
1431 throw new IllegalArgumentException(
1432 "(nHexs-1)*4+srcPos is greather or equal to than 32");
1433 }
1434 final StringBuilder sb = new StringBuilder(dstInit);
1435 int shift = 0;
1436 int append = sb.length();
1437 for (int i = 0; i < nHexs; i++ ) {
1438 shift = i * 4 + srcPos;
1439 final int bits = 0xF & (src >> shift);
1440 if (dstPos + i == append) {
1441 ++append;
1442 sb.append(intToHexDigit(bits));
1443 } else {
1444 sb.setCharAt(dstPos + i, intToHexDigit(bits));
1445 }
1446 }
1447 return sb.toString();
1448 }
1449
1450 /**
1451 * <p>
1452 * Converts a short into an array of Char using the default (little endian, Lsb0) byte and
1453 * bit ordering.
1454 * </p>
1455 *
1456 * @param src the short to convert
1457 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1458 * @param dstInit the initial value for the result String
1459 * @param dstPos the position in {@code dst} where to copy the result
1460 * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
1461 * width of the input (from srcPos to msb)
1462 * @return {@code dst}
1463 * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 16}
1464 * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
1465 */
1466 public static String shortToHex(final short src, final int srcPos, final String dstInit, final int dstPos, final int nHexs) {
1467 if (0 == nHexs) {
1468 return dstInit;
1469 }
1470 if ((nHexs - 1) * 4 + srcPos >= 16) {
1471 throw new IllegalArgumentException(
1472 "(nHexs-1)*4+srcPos is greather or equal to than 16");
1473 }
1474 final StringBuilder sb = new StringBuilder(dstInit);
1475 int shift = 0;
1476 int append = sb.length();
1477 for (int i = 0; i < nHexs; i++ ) {
1478 shift = i * 4 + srcPos;
1479 final int bits = 0xF & (src >> shift);
1480 if (dstPos + i == append) {
1481 ++append;
1482 sb.append(intToHexDigit(bits));
1483 } else {
1484 sb.setCharAt(dstPos + i, intToHexDigit(bits));
1485 }
1486 }
1487 return sb.toString();
1488 }
1489
1490 /**
1491 * <p>
1492 * Converts a byte into an array of Char using the default (little endian, Lsb0) byte and
1493 * bit ordering.
1494 * </p>
1495 *
1496 * @param src the byte to convert
1497 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1498 * @param dstInit the initial value for the result String
1499 * @param dstPos the position in {@code dst} where to copy the result
1500 * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
1501 * width of the input (from srcPos to msb)
1502 * @return {@code dst}
1503 * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 8}
1504 * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
1505 */
1506 public static String byteToHex(final byte src, final int srcPos, final String dstInit, final int dstPos, final int nHexs) {
1507 if (0 == nHexs) {
1508 return dstInit;
1509 }
1510 if ((nHexs - 1) * 4 + srcPos >= 8) {
1511 throw new IllegalArgumentException(
1512 "(nHexs-1)*4+srcPos is greather or equal to than 8");
1513 }
1514 final StringBuilder sb = new StringBuilder(dstInit);
1515 int shift = 0;
1516 int append = sb.length();
1517 for (int i = 0; i < nHexs; i++ ) {
1518 shift = i * 4 + srcPos;
1519 final int bits = 0xF & (src >> shift);
1520 if (dstPos + i == append) {
1521 ++append;
1522 sb.append(intToHexDigit(bits));
1523 } else {
1524 sb.setCharAt(dstPos + i, intToHexDigit(bits));
1525 }
1526 }
1527 return sb.toString();
1528 }
1529
1530 /**
1531 * <p>
1532 * Converts a long into an array of boolean using the default (little endian, Lsb0) byte and
1533 * bit ordering.
1534 * </p>
1535 *
1536 * @param src the long to convert
1537 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1538 * @param dst the destination array
1539 * @param dstPos the position in {@code dst} where to copy the result
1540 * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
1541 * the width of the input (from srcPos to msb)
1542 * @return {@code dst}
1543 * @throws NullPointerException if {@code dst} is {@code null}
1544 * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 64}
1545 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
1546 */
1547 public static boolean[] longToBinary(final long src, final int srcPos, final boolean[] dst, final int dstPos,
1548 final int nBools) {
1549 if (0 == nBools) {
1550 return dst;
1551 }
1552 if (nBools - 1 + srcPos >= 64) {
1553 throw new IllegalArgumentException(
1554 "nBools-1+srcPos is greather or equal to than 64");
1555 }
1556 int shift = 0;
1557 for (int i = 0; i < nBools; i++ ) {
1558 shift = i * 1 + srcPos;
1559 dst[dstPos + i] = ((0x1 & (src >> shift)) != 0);
1560 }
1561 return dst;
1562 }
1563
1564 /**
1565 * <p>
1566 * Converts a int into an array of boolean using the default (little endian, Lsb0) byte and
1567 * bit ordering.
1568 * </p>
1569 *
1570 * @param src the int to convert
1571 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1572 * @param dst the destination array
1573 * @param dstPos the position in {@code dst} where to copy the result
1574 * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
1575 * the width of the input (from srcPos to msb)
1576 * @return {@code dst}
1577 * @throws NullPointerException if {@code dst} is {@code null}
1578 * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 32}
1579 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
1580 */
1581 public static boolean[] intToBinary(final int src, final int srcPos, final boolean[] dst, final int dstPos,
1582 final int nBools) {
1583 if (0 == nBools) {
1584 return dst;
1585 }
1586 if (nBools - 1 + srcPos >= 32) {
1587 throw new IllegalArgumentException(
1588 "nBools-1+srcPos is greather or equal to than 32");
1589 }
1590 int shift = 0;
1591 for (int i = 0; i < nBools; i++ ) {
1592 shift = i * 1 + srcPos;
1593 dst[dstPos + i] = ((0x1 & (src >> shift)) != 0);
1594 }
1595 return dst;
1596 }
1597
1598 /**
1599 * <p>
1600 * Converts a short into an array of boolean using the default (little endian, Lsb0) byte
1601 * and bit ordering.
1602 * </p>
1603 *
1604 * @param src the short to convert
1605 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1606 * @param dst the destination array
1607 * @param dstPos the position in {@code dst} where to copy the result
1608 * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
1609 * the width of the input (from srcPos to msb)
1610 * @return {@code dst}
1611 * @throws NullPointerException if {@code dst} is {@code null}
1612 * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 16}
1613 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
1614 */
1615 public static boolean[] shortToBinary(final short src, final int srcPos, final boolean[] dst, final int dstPos,
1616 final int nBools) {
1617 if (0 == nBools) {
1618 return dst;
1619 }
1620 if (nBools - 1 + srcPos >= 16) {
1621 throw new IllegalArgumentException(
1622 "nBools-1+srcPos is greather or equal to than 16");
1623 }
1624 int shift = 0;
1625 assert ((nBools - 1) * 1 < 16 - srcPos);
1626 for (int i = 0; i < nBools; i++ ) {
1627 shift = i * 1 + srcPos;
1628 dst[dstPos + i] = ((0x1 & (src >> shift)) != 0);
1629 }
1630 return dst;
1631 }
1632
1633 /**
1634 * <p>
1635 * Converts a byte into an array of boolean using the default (little endian, Lsb0) byte and
1636 * bit ordering.
1637 * </p>
1638 *
1639 * @param src the byte to convert
1640 * @param srcPos the position in {@code src}, in bits, from where to start the conversion
1641 * @param dst the destination array
1642 * @param dstPos the position in {@code dst} where to copy the result
1643 * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
1644 * the width of the input (from srcPos to msb)
1645 * @return {@code dst}
1646 * @throws NullPointerException if {@code dst} is {@code null}
1647 * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 8}
1648 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
1649 */
1650 public static boolean[] byteToBinary(final byte src, final int srcPos, final boolean[] dst, final int dstPos,
1651 final int nBools) {
1652 if (0 == nBools) {
1653 return dst;
1654 }
1655 if (nBools - 1 + srcPos >= 8) {
1656 throw new IllegalArgumentException("nBools-1+srcPos is greather or equal to than 8");
1657 }
1658 int shift = 0;
1659 for (int i = 0; i < nBools; i++ ) {
1660 shift = i * 1 + srcPos;
1661 dst[dstPos + i] = ((0x1 & (src >> shift)) != 0);
1662 }
1663 return dst;
1664 }
1665
1666 /**
1667 * <p>
1668 * Converts UUID into an array of byte using the default (little endian, Lsb0) byte and bit
1669 * ordering.
1670 * </p>
1671 *
1672 * @param src the UUID to convert
1673 * @param dst the destination array
1674 * @param dstPos the position in {@code dst} where to copy the result
1675 * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
1676 * width of the input (from srcPos to msb)
1677 * @return {@code dst}
1678 * @throws NullPointerException if {@code dst} is {@code null}
1679 * @throws IllegalArgumentException if {@code nBytes > 16}
1680 * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
1681 */
1682 public static byte[] uuidToByteArray(final UUID src, final byte[] dst, final int dstPos, final int nBytes) {
1683 if (0 == nBytes) {
1684 return dst;
1685 }
1686 if (nBytes > 16) {
1687 throw new IllegalArgumentException("nBytes is greather than 16");
1688 }
1689 longToByteArray(src.getMostSignificantBits(), 0, dst, dstPos, nBytes > 8 ? 8 : nBytes);
1690 if (nBytes >= 8) {
1691 longToByteArray(src.getLeastSignificantBits(), 0, dst, dstPos + 8, nBytes - 8);
1692 }
1693 return dst;
1694 }
1695
1696 /**
1697 * <p>
1698 * Converts bytes from an array into a UUID using the default (little endian, Lsb0) byte and
1699 * bit ordering.
1700 * </p>
1701 *
1702 * @param src the byte array to convert
1703 * @param srcPos the position in {@code src} where to copy the result from
1704 * @return a UUID
1705 * @throws NullPointerException if {@code src} is {@code null}
1706 * @throws IllegalArgumentException if array does not contain at least 16 bytes beginning
1707 * with {@code srcPos}
1708 */
1709 public static UUID byteArrayToUuid(final byte[] src, final int srcPos) {
1710 if (src.length - srcPos < 16) {
1711 throw new IllegalArgumentException("Need at least 16 bytes for UUID");
1712 }
1713 return new UUID(byteArrayToLong(src, srcPos, 0, 0, 8), byteArrayToLong(
1714 src, srcPos + 8, 0, 0, 8));
1715 }
1716 }
1717
1818 import java.util.ArrayList;
1919 import java.util.Arrays;
20 import java.util.Collections;
21 import java.util.EnumSet;
2022 import java.util.LinkedHashMap;
2123 import java.util.List;
2224 import java.util.Map;
23 import java.util.EnumSet;
2425
2526 /**
2627 * <p>Utility library to provide helper methods for Java enums.</p>
2829 * <p>#ThreadSafe#</p>
2930 *
3031 * @since 3.0
31 * @version $Id: EnumUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
32 * @version $Id: EnumUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3233 */
3334 public class EnumUtils {
3435
36 private static final String NULL_ELEMENTS_NOT_PERMITTED = "null elements not permitted";
37 private static final String CANNOT_STORE_S_S_VALUES_IN_S_BITS = "Cannot store %s %s values in %s bits";
38 private static final String S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE = "%s does not seem to be an Enum type";
39 private static final String ENUM_CLASS_MUST_BE_DEFINED = "EnumClass must be defined.";
40
3541 /**
3642 * This constructor is public to permit tools that require a JavaBean
3743 * instance to operate.
4854 * @param enumClass the class of the enum to query, not null
4955 * @return the modifiable map of enum names to enums, never null
5056 */
51 public static <E extends Enum<E>> Map<String, E> getEnumMap(Class<E> enumClass) {
52 Map<String, E> map = new LinkedHashMap<String, E>();
53 for (E e: enumClass.getEnumConstants()) {
57 public static <E extends Enum<E>> Map<String, E> getEnumMap(final Class<E> enumClass) {
58 final Map<String, E> map = new LinkedHashMap<String, E>();
59 for (final E e: enumClass.getEnumConstants()) {
5460 map.put(e.name(), e);
5561 }
5662 return map;
6571 * @param enumClass the class of the enum to query, not null
6672 * @return the modifiable list of enums, never null
6773 */
68 public static <E extends Enum<E>> List<E> getEnumList(Class<E> enumClass) {
74 public static <E extends Enum<E>> List<E> getEnumList(final Class<E> enumClass) {
6975 return new ArrayList<E>(Arrays.asList(enumClass.getEnumConstants()));
7076 }
7177
8086 * @param enumName the enum name, null returns false
8187 * @return true if the enum name is valid, otherwise false
8288 */
83 public static <E extends Enum<E>> boolean isValidEnum(Class<E> enumClass, String enumName) {
89 public static <E extends Enum<E>> boolean isValidEnum(final Class<E> enumClass, final String enumName) {
8490 if (enumName == null) {
8591 return false;
8692 }
8793 try {
8894 Enum.valueOf(enumClass, enumName);
8995 return true;
90 } catch (IllegalArgumentException ex) {
96 } catch (final IllegalArgumentException ex) {
9197 return false;
9298 }
9399 }
103109 * @param enumName the enum name, null returns null
104110 * @return the enum, null if not found
105111 */
106 public static <E extends Enum<E>> E getEnum(Class<E> enumClass, String enumName) {
112 public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) {
107113 if (enumName == null) {
108114 return null;
109115 }
110116 try {
111117 return Enum.valueOf(enumClass, enumName);
112 } catch (IllegalArgumentException ex) {
118 } catch (final IllegalArgumentException ex) {
113119 return null;
114120 }
115121 }
123129 * would create a value greater than a long can hold.</p>
124130 *
125131 * @param enumClass the class of the enum we are working with, not {@code null}
132 * @param values the values we want to convert, not {@code null}, neither containing {@code null}
133 * @param <E> the type of the enumeration
134 * @return a long whose value provides a binary representation of the given set of enum values.
135 * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
136 * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values,
137 * or if any {@code values} {@code null}
138 * @since 3.0.1
139 * @see #generateBitVectors(Class, Iterable)
140 */
141 public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass, final Iterable<E> values) {
142 checkBitVectorable(enumClass);
143 Validate.notNull(values);
144 long total = 0;
145 for (final E constant : values) {
146 Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
147 total |= 1 << constant.ordinal();
148 }
149 return total;
150 }
151
152 /**
153 * <p>Creates a bit vector representation of the given subset of an Enum using as many {@code long}s as needed.</p>
154 *
155 * <p>This generates a value that is usable by {@link EnumUtils#processBitVectors}.</p>
156 *
157 * <p>Use this method if you have more than 64 values in your Enum.</p>
158 *
159 * @param enumClass the class of the enum we are working with, not {@code null}
160 * @param values the values we want to convert, not {@code null}, neither containing {@code null}
161 * @param <E> the type of the enumeration
162 * @return a long[] whose values provide a binary representation of the given set of enum values
163 * with least significant digits rightmost.
164 * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
165 * @throws IllegalArgumentException if {@code enumClass} is not an enum class, or if any {@code values} {@code null}
166 * @since 3.2
167 */
168 public static <E extends Enum<E>> long[] generateBitVectors(final Class<E> enumClass, final Iterable<E> values) {
169 asEnum(enumClass);
170 Validate.notNull(values);
171 final EnumSet<E> condensed = EnumSet.noneOf(enumClass);
172 for (final E constant : values) {
173 Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
174 condensed.add(constant);
175 }
176 final long[] result = new long[(enumClass.getEnumConstants().length - 1) / Long.SIZE + 1];
177 for (final E value : condensed) {
178 result[value.ordinal() / Long.SIZE] |= 1 << (value.ordinal() % Long.SIZE);
179 }
180 ArrayUtils.reverse(result);
181 return result;
182 }
183
184 /**
185 * <p>Creates a long bit vector representation of the given array of Enum values.</p>
186 *
187 * <p>This generates a value that is usable by {@link EnumUtils#processBitVector}.</p>
188 *
189 * <p>Do not use this method if you have more than 64 values in your Enum, as this
190 * would create a value greater than a long can hold.</p>
191 *
192 * @param enumClass the class of the enum we are working with, not {@code null}
126193 * @param values the values we want to convert, not {@code null}
127194 * @param <E> the type of the enumeration
128 * @return a long whose binary value represents the given set of enum values.
195 * @return a long whose value provides a binary representation of the given set of enum values.
129196 * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
130197 * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
131198 * @since 3.0.1
132 */
133 public static <E extends Enum<E>> long generateBitVector(Class<E> enumClass, Iterable<E> values) {
134 checkBitVectorable(enumClass);
135 Validate.notNull(values);
136 long total = 0;
137 for (E constant : values) {
138 total |= 1 << constant.ordinal();
139 }
140 return total;
141 }
142
143 /**
144 * <p>Creates a long bit vector representation of the given array of Enum values.</p>
145 *
146 * <p>This generates a value that is usable by {@link EnumUtils#processBitVector}.</p>
147 *
148 * <p>Do not use this method if you have more than 64 values in your Enum, as this
149 * would create a value greater than a long can hold.</p>
150 *
151 * @param enumClass the class of the enum we are working with, not {@code null}
152 * @param values the values we want to convert, not {@code null}
153 * @param <E> the type of the enumeration
154 * @return a long whose binary value represents the given set of enum values.
155 * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
156 * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
157 * @since 3.0.1
158 */
159 public static <E extends Enum<E>> long generateBitVector(Class<E> enumClass, E... values) {
199 * @see #generateBitVectors(Class, Iterable)
200 */
201 public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass, final E... values) {
160202 Validate.noNullElements(values);
161203 return generateBitVector(enumClass, Arrays.<E> asList(values));
204 }
205
206 /**
207 * <p>Creates a bit vector representation of the given subset of an Enum using as many {@code long}s as needed.</p>
208 *
209 * <p>This generates a value that is usable by {@link EnumUtils#processBitVectors}.</p>
210 *
211 * <p>Use this method if you have more than 64 values in your Enum.</p>
212 *
213 * @param enumClass the class of the enum we are working with, not {@code null}
214 * @param values the values we want to convert, not {@code null}, neither containing {@code null}
215 * @param <E> the type of the enumeration
216 * @return a long[] whose values provide a binary representation of the given set of enum values
217 * with least significant digits rightmost.
218 * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
219 * @throws IllegalArgumentException if {@code enumClass} is not an enum class, or if any {@code values} {@code null}
220 * @since 3.2
221 */
222 public static <E extends Enum<E>> long[] generateBitVectors(final Class<E> enumClass, final E... values) {
223 asEnum(enumClass);
224 Validate.noNullElements(values);
225 final EnumSet<E> condensed = EnumSet.noneOf(enumClass);
226 Collections.addAll(condensed, values);
227 final long[] result = new long[(enumClass.getEnumConstants().length - 1) / Long.SIZE + 1];
228 for (final E value : condensed) {
229 result[value.ordinal() / Long.SIZE] |= 1 << (value.ordinal() % Long.SIZE);
230 }
231 ArrayUtils.reverse(result);
232 return result;
162233 }
163234
164235 /**
174245 * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
175246 * @since 3.0.1
176247 */
177 public static <E extends Enum<E>> EnumSet<E> processBitVector(Class<E> enumClass, long value) {
178 final E[] constants = checkBitVectorable(enumClass).getEnumConstants();
179 final EnumSet<E> results = EnumSet.noneOf(enumClass);
180 for (E constant : constants) {
181 if ((value & 1 << constant.ordinal()) != 0) {
248 public static <E extends Enum<E>> EnumSet<E> processBitVector(final Class<E> enumClass, final long value) {
249 checkBitVectorable(enumClass).getEnumConstants();
250 return processBitVectors(enumClass, value);
251 }
252
253 /**
254 * <p>Convert a {@code long[]} created by {@link EnumUtils#generateBitVectors} into the set of
255 * enum values that it represents.</p>
256 *
257 * <p>If you store this value, beware any changes to the enum that would affect ordinal values.</p>
258 * @param enumClass the class of the enum we are working with, not {@code null}
259 * @param values the long[] bearing the representation of a set of enum values, least significant digits rightmost, not {@code null}
260 * @param <E> the type of the enumeration
261 * @return a set of enum values
262 * @throws NullPointerException if {@code enumClass} is {@code null}
263 * @throws IllegalArgumentException if {@code enumClass} is not an enum class
264 * @since 3.2
265 */
266 public static <E extends Enum<E>> EnumSet<E> processBitVectors(final Class<E> enumClass, long... values) {
267 final EnumSet<E> results = EnumSet.noneOf(asEnum(enumClass));
268 values = ArrayUtils.clone(Validate.notNull(values));
269 ArrayUtils.reverse(values);
270 for (final E constant : enumClass.getEnumConstants()) {
271 final int block = constant.ordinal() / Long.SIZE;
272 if (block < values.length && (values[block] & 1 << (constant.ordinal() % Long.SIZE)) != 0) {
182273 results.add(constant);
183274 }
184275 }
194285 * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values
195286 * @since 3.0.1
196287 */
197 private static <E extends Enum<E>> Class<E> checkBitVectorable(Class<E> enumClass) {
198 Validate.notNull(enumClass, "EnumClass must be defined.");
199
200 final E[] constants = enumClass.getEnumConstants();
201 Validate.isTrue(constants != null, "%s does not seem to be an Enum type", enumClass);
202 Validate.isTrue(constants.length <= Long.SIZE, "Cannot store %s %s values in %s bits", constants.length,
288 private static <E extends Enum<E>> Class<E> checkBitVectorable(final Class<E> enumClass) {
289 final E[] constants = asEnum(enumClass).getEnumConstants();
290 Validate.isTrue(constants.length <= Long.SIZE, CANNOT_STORE_S_S_VALUES_IN_S_BITS, constants.length,
203291 enumClass.getSimpleName(), Long.SIZE);
204292
205293 return enumClass;
206294 }
295
296 /**
297 * Validate {@code enumClass}.
298 * @param <E> the type of the enumeration
299 * @param enumClass to check
300 * @return {@code enumClass}
301 * @throws NullPointerException if {@code enumClass} is {@code null}
302 * @throws IllegalArgumentException if {@code enumClass} is not an enum class
303 * @since 3.2
304 */
305 private static <E extends Enum<E>> Class<E> asEnum(final Class<E> enumClass) {
306 Validate.notNull(enumClass, ENUM_CLASS_MUST_BE_DEFINED);
307 Validate.isTrue(enumClass.isEnum(), S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE, enumClass);
308 return enumClass;
309 }
207310 }
100100 * @param requiredVersion the version to check against, not null
101101 * @return true if this version is equal to or greater than the specified version
102102 */
103 public boolean atLeast(JavaVersion requiredVersion) {
103 public boolean atLeast(final JavaVersion requiredVersion) {
104104 return this.value >= requiredVersion.value;
105105 }
106106
3333 * Each method documents its behaviour in more detail.</p>
3434 *
3535 * @since 2.2
36 * @version $Id: LocaleUtils.java 1090563 2011-04-09 11:00:10Z sebb $
36 * @version $Id: LocaleUtils.java 1555043 2014-01-03 10:26:54Z britter $
3737 */
3838 public class LocaleUtils {
3939
6464 * locale object from it.</p>
6565 *
6666 * <pre>
67 * LocaleUtils.toLocale("") = new Locale("", "")
6768 * LocaleUtils.toLocale("en") = new Locale("en", "")
6869 * LocaleUtils.toLocale("en_GB") = new Locale("en", "GB")
6970 * LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#)
8384 * @param str the locale String to convert, null returns null
8485 * @return a Locale, null if null input
8586 * @throws IllegalArgumentException if the string is an invalid format
86 */
87 public static Locale toLocale(String str) {
87 * @see Locale#forLanguageTag(String)
88 */
89 public static Locale toLocale(final String str) {
8890 if (str == null) {
8991 return null;
9092 }
91 int len = str.length();
92 if (len != 2 && len != 5 && len < 7) {
93 throw new IllegalArgumentException("Invalid locale format: " + str);
94 }
95 char ch0 = str.charAt(0);
96 char ch1 = str.charAt(1);
97 if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {
93 if (str.isEmpty()) { // LANG-941 - JDK 8 introduced an empty locale where all fields are blank
94 return new Locale("", "");
95 }
96 if (str.contains("#")) { // LANG-879 - Cannot handle Java 7 script & extensions
97 throw new IllegalArgumentException("Invalid locale format: " + str);
98 }
99 final int len = str.length();
100 if (len < 2) {
101 throw new IllegalArgumentException("Invalid locale format: " + str);
102 }
103 final char ch0 = str.charAt(0);
104 if (ch0 == '_') {
105 if (len < 3) {
106 throw new IllegalArgumentException("Invalid locale format: " + str);
107 }
108 final char ch1 = str.charAt(1);
109 final char ch2 = str.charAt(2);
110 if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
111 throw new IllegalArgumentException("Invalid locale format: " + str);
112 }
113 if (len == 3) {
114 return new Locale("", str.substring(1, 3));
115 }
116 if (len < 5) {
117 throw new IllegalArgumentException("Invalid locale format: " + str);
118 }
119 if (str.charAt(3) != '_') {
120 throw new IllegalArgumentException("Invalid locale format: " + str);
121 }
122 return new Locale("", str.substring(1, 3), str.substring(4));
123 }
124 final char ch1 = str.charAt(1);
125 if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {
98126 throw new IllegalArgumentException("Invalid locale format: " + str);
99127 }
100128 if (len == 2) {
101 return new Locale(str, "");
102 } else {
103 if (str.charAt(2) != '_') {
104 throw new IllegalArgumentException("Invalid locale format: " + str);
105 }
106 char ch3 = str.charAt(3);
107 if (ch3 == '_') {
108 return new Locale(str.substring(0, 2), "", str.substring(4));
109 }
110 char ch4 = str.charAt(4);
111 if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {
112 throw new IllegalArgumentException("Invalid locale format: " + str);
113 }
114 if (len == 5) {
115 return new Locale(str.substring(0, 2), str.substring(3, 5));
116 } else {
117 if (str.charAt(5) != '_') {
118 throw new IllegalArgumentException("Invalid locale format: " + str);
119 }
120 return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
121 }
122 }
129 return new Locale(str);
130 }
131 if (len < 5) {
132 throw new IllegalArgumentException("Invalid locale format: " + str);
133 }
134 if (str.charAt(2) != '_') {
135 throw new IllegalArgumentException("Invalid locale format: " + str);
136 }
137 final char ch3 = str.charAt(3);
138 if (ch3 == '_') {
139 return new Locale(str.substring(0, 2), "", str.substring(4));
140 }
141 final char ch4 = str.charAt(4);
142 if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {
143 throw new IllegalArgumentException("Invalid locale format: " + str);
144 }
145 if (len == 5) {
146 return new Locale(str.substring(0, 2), str.substring(3, 5));
147 }
148 if (len < 7) {
149 throw new IllegalArgumentException("Invalid locale format: " + str);
150 }
151 if (str.charAt(5) != '_') {
152 throw new IllegalArgumentException("Invalid locale format: " + str);
153 }
154 return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
123155 }
124156
125157 //-----------------------------------------------------------------------
135167 * @param locale the locale to start from
136168 * @return the unmodifiable list of Locale objects, 0 being locale, not null
137169 */
138 public static List<Locale> localeLookupList(Locale locale) {
170 public static List<Locale> localeLookupList(final Locale locale) {
139171 return localeLookupList(locale, locale);
140172 }
141173
157189 * @param defaultLocale the default locale to use if no other is found
158190 * @return the unmodifiable list of Locale objects, 0 being locale, not null
159191 */
160 public static List<Locale> localeLookupList(Locale locale, Locale defaultLocale) {
161 List<Locale> list = new ArrayList<Locale>(4);
192 public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale) {
193 final List<Locale> list = new ArrayList<Locale>(4);
162194 if (locale != null) {
163195 list.add(locale);
164196 if (locale.getVariant().length() > 0) {
209241 * @param locale the Locale object to check if it is available
210242 * @return true if the locale is a known locale
211243 */
212 public static boolean isAvailableLocale(Locale locale) {
244 public static boolean isAvailableLocale(final Locale locale) {
213245 return availableLocaleList().contains(locale);
214246 }
215247
223255 * @param countryCode the 2 letter country code, null returns empty
224256 * @return an unmodifiable List of Locale objects, not null
225257 */
226 public static List<Locale> languagesByCountry(String countryCode) {
258 public static List<Locale> languagesByCountry(final String countryCode) {
227259 if (countryCode == null) {
228260 return Collections.emptyList();
229261 }
230262 List<Locale> langs = cLanguagesByCountry.get(countryCode);
231263 if (langs == null) {
232264 langs = new ArrayList<Locale>();
233 List<Locale> locales = availableLocaleList();
265 final List<Locale> locales = availableLocaleList();
234266 for (int i = 0; i < locales.size(); i++) {
235 Locale locale = locales.get(i);
267 final Locale locale = locales.get(i);
236268 if (countryCode.equals(locale.getCountry()) &&
237 locale.getVariant().length() == 0) {
269 locale.getVariant().isEmpty()) {
238270 langs.add(locale);
239271 }
240272 }
255287 * @param languageCode the 2 letter language code, null returns empty
256288 * @return an unmodifiable List of Locale objects, not null
257289 */
258 public static List<Locale> countriesByLanguage(String languageCode) {
290 public static List<Locale> countriesByLanguage(final String languageCode) {
259291 if (languageCode == null) {
260292 return Collections.emptyList();
261293 }
262294 List<Locale> countries = cCountriesByLanguage.get(languageCode);
263295 if (countries == null) {
264296 countries = new ArrayList<Locale>();
265 List<Locale> locales = availableLocaleList();
297 final List<Locale> locales = availableLocaleList();
266298 for (int i = 0; i < locales.size(); i++) {
267 Locale locale = locales.get(i);
299 final Locale locale = locales.get(i);
268300 if (languageCode.equals(locale.getLanguage()) &&
269301 locale.getCountry().length() != 0 &&
270 locale.getVariant().length() == 0) {
302 locale.getVariant().isEmpty()) {
271303 countries.add(locale);
272304 }
273305 }
279311 }
280312
281313 //-----------------------------------------------------------------------
282 // class to avoid synchronization
314 // class to avoid synchronization (Init on demand)
283315 static class SyncAvoid {
284316 /** Unmodifiable list of available locales. */
285 private static List<Locale> AVAILABLE_LOCALE_LIST;
317 private static final List<Locale> AVAILABLE_LOCALE_LIST;
286318 /** Unmodifiable set of available locales. */
287 private static Set<Locale> AVAILABLE_LOCALE_SET;
319 private static final Set<Locale> AVAILABLE_LOCALE_SET;
288320
289321 static {
290 List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales())); // extra safe
322 final List<Locale> list = new ArrayList<Locale>(Arrays.asList(Locale.getAvailableLocales())); // extra safe
291323 AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
292 AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(availableLocaleList()));
324 AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<Locale>(list));
293325 }
294326 }
295327
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3;
17
18 /**
19 * <p>Thrown to indicate that a block of code has not been implemented.
20 * This exception supplements <code>UnsupportedOperationException</code>
21 * by providing a more semantically rich description of the problem.</p>
22 *
23 * <p><code>NotImplementedException</code> represents the case where the
24 * author has yet to implement the logic at this point in the program.
25 * This can act as an exception based TODO tag. </p>
26 *
27 * <pre>
28 * public void foo() {
29 * try {
30 * // do something that throws an Exception
31 * } catch (Exception ex) {
32 * // don't know what to do here yet
33 * throw new NotImplementedException("TODO", ex);
34 * }
35 * }
36 * </pre>
37 *
38 * This class was originally added in Lang 2.0, but removed in 3.0.
39 *
40 * @since 3.2
41 * @version $Id: NotImplementedException.java 905636 2010-02-02 14:03:32Z niallp $
42 */
43 public class NotImplementedException extends UnsupportedOperationException {
44
45 private static final long serialVersionUID = 20131021L;
46
47 private String code;
48
49 /**
50 * Constructs a NotImplementedException.
51 *
52 * @param message description of the exception
53 * @since 3.2
54 */
55 public NotImplementedException(final String message) {
56 super(message);
57 }
58
59 /**
60 * Constructs a NotImplementedException.
61 *
62 * @param cause cause of the exception
63 * @since 3.2
64 */
65 public NotImplementedException(final Throwable cause) {
66 super(cause);
67 }
68
69 /**
70 * Constructs a NotImplementedException.
71 *
72 * @param message description of the exception
73 * @param cause cause of the exception
74 * @since 3.2
75 */
76 public NotImplementedException(final String message, final Throwable cause) {
77 super(message, cause);
78 }
79
80 /**
81 * Constructs a NotImplementedException.
82 *
83 * @param message description of the exception
84 * @param code code indicating a resource for more information regarding the lack of implementation
85 * @since 3.2
86 */
87 public NotImplementedException(final String message, final String code) {
88 super(message);
89 this.code = code;
90 }
91
92 /**
93 * Constructs a NotImplementedException.
94 *
95 * @param cause cause of the exception
96 * @param code code indicating a resource for more information regarding the lack of implementation
97 * @since 3.2
98 */
99 public NotImplementedException(final Throwable cause, final String code) {
100 super(cause);
101 this.code = code;
102 }
103
104 /**
105 * Constructs a NotImplementedException.
106 *
107 * @param message description of the exception
108 * @param cause cause of the exception
109 * @param code code indicating a resource for more information regarding the lack of implementation
110 * @since 3.2
111 */
112 public NotImplementedException(final String message, final Throwable cause, final String code) {
113 super(message, cause);
114 this.code = code;
115 }
116
117 /**
118 * Obtain the not implemented code. This is an unformatted piece of text intended to point to
119 * further information regarding the lack of implementation. It might, for example, be an issue
120 * tracker ID or a URL.
121 *
122 * @return a code indicating a resource for more information regarding the lack of implementation
123 */
124 public String getCode() {
125 return this.code;
126 }
127 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import java.io.IOException;
1819 import java.io.Serializable;
1920 import java.lang.reflect.Array;
2021 import java.lang.reflect.InvocationTargetException;
2728
2829 import org.apache.commons.lang3.exception.CloneFailedException;
2930 import org.apache.commons.lang3.mutable.MutableInt;
31 import org.apache.commons.lang3.text.StrBuilder;
3032
3133 /**
3234 * <p>Operations on {@code Object}.</p>
3739 *
3840 * <p>#ThreadSafe#</p>
3941 * @since 1.0
40 * @version $Id: ObjectUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
42 * @version $Id: ObjectUtils.java 1553927 2013-12-28 21:17:57Z ggregory $
4143 */
4244 //@Immutable
4345 public class ObjectUtils {
8991 * @param defaultValue the default value to return, may be {@code null}
9092 * @return {@code object} if it is not {@code null}, defaultValue otherwise
9193 */
92 public static <T> T defaultIfNull(T object, T defaultValue) {
94 public static <T> T defaultIfNull(final T object, final T defaultValue) {
9395 return object != null ? object : defaultValue;
9496 }
9597
115117 * or {@code null} if there are no non-null values
116118 * @since 3.0
117119 */
118 public static <T> T firstNonNull(T... values) {
120 public static <T> T firstNonNull(final T... values) {
119121 if (values != null) {
120 for (T val : values) {
122 for (final T val : values) {
121123 if (val != null) {
122124 return val;
123125 }
146148 * @param object1 the first object, may be {@code null}
147149 * @param object2 the second object, may be {@code null}
148150 * @return {@code true} if the values of both objects are the same
149 */
150 public static boolean equals(Object object1, Object object2) {
151 * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will
152 * be removed from future releases.
153 */
154 @Deprecated
155 public static boolean equals(final Object object1, final Object object2) {
151156 if (object1 == object2) {
152157 return true;
153158 }
176181 * @param object2 the second object, may be {@code null}
177182 * @return {@code false} if the values of both objects are the same
178183 */
179 public static boolean notEqual(Object object1, Object object2) {
184 public static boolean notEqual(final Object object1, final Object object2) {
180185 return ObjectUtils.equals(object1, object2) == false;
181186 }
182187
192197 * @param obj the object to obtain the hash code of, may be {@code null}
193198 * @return the hash code of the object, or zero if null
194199 * @since 2.1
195 */
196 public static int hashCode(Object obj) {
200 * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be
201 * removed in future releases
202 */
203 @Deprecated
204 public static int hashCode(final Object obj) {
197205 // hashCode(Object) retained for performance, as hash code is often critical
198206 return obj == null ? 0 : obj.hashCode();
199207 }
217225 * @param objects the objects to obtain the hash code of, may be {@code null}
218226 * @return the hash code of the objects, or zero if null
219227 * @since 3.0
220 */
221 public static int hashCodeMulti(Object... objects) {
228 * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 an will be
229 * removed in future releases.
230 */
231 @Deprecated
232 public static int hashCodeMulti(final Object... objects) {
222233 int hash = 1;
223234 if (objects != null) {
224 for (Object object : objects) {
235 for (final Object object : objects) {
225236 hash = hash * 31 + ObjectUtils.hashCode(object);
226237 }
227238 }
246257 * @return the default toString text, or {@code null} if
247258 * {@code null} passed in
248259 */
249 public static String identityToString(Object object) {
260 public static String identityToString(final Object object) {
250261 if (object == null) {
251262 return null;
252263 }
253 StringBuffer buffer = new StringBuffer();
254 identityToString(buffer, object);
255 return buffer.toString();
264 final StringBuilder builder = new StringBuilder();
265 identityToString(builder, object);
266 return builder.toString();
256267 }
257268
258269 /**
261272 * will throw a NullPointerException for either of the two parameters. </p>
262273 *
263274 * <pre>
275 * ObjectUtils.identityToString(appendable, "") = appendable.append("java.lang.String@1e23"
276 * ObjectUtils.identityToString(appendable, Boolean.TRUE) = appendable.append("java.lang.Boolean@7fa"
277 * ObjectUtils.identityToString(appendable, Boolean.TRUE) = appendable.append("java.lang.Boolean@7fa")
278 * </pre>
279 *
280 * @param appendable the appendable to append to
281 * @param object the object to create a toString for
282 * @throws IOException
283 * @since 3.2
284 */
285 public static void identityToString(final Appendable appendable, final Object object) throws IOException {
286 if (object == null) {
287 throw new NullPointerException("Cannot get the toString of a null identity");
288 }
289 appendable.append(object.getClass().getName())
290 .append('@')
291 .append(Integer.toHexString(System.identityHashCode(object)));
292 }
293
294 /**
295 * <p>Appends the toString that would be produced by {@code Object}
296 * if a class did not override toString itself. {@code null}
297 * will throw a NullPointerException for either of the two parameters. </p>
298 *
299 * <pre>
300 * ObjectUtils.identityToString(builder, "") = builder.append("java.lang.String@1e23"
301 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa"
302 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa")
303 * </pre>
304 *
305 * @param builder the builder to append to
306 * @param object the object to create a toString for
307 * @since 3.2
308 */
309 public static void identityToString(final StrBuilder builder, final Object object) {
310 if (object == null) {
311 throw new NullPointerException("Cannot get the toString of a null identity");
312 }
313 builder.append(object.getClass().getName())
314 .append('@')
315 .append(Integer.toHexString(System.identityHashCode(object)));
316 }
317
318 /**
319 * <p>Appends the toString that would be produced by {@code Object}
320 * if a class did not override toString itself. {@code null}
321 * will throw a NullPointerException for either of the two parameters. </p>
322 *
323 * <pre>
264324 * ObjectUtils.identityToString(buf, "") = buf.append("java.lang.String@1e23"
265325 * ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa"
266326 * ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa")
270330 * @param object the object to create a toString for
271331 * @since 2.4
272332 */
273 public static void identityToString(StringBuffer buffer, Object object) {
333 public static void identityToString(final StringBuffer buffer, final Object object) {
274334 if (object == null) {
275335 throw new NullPointerException("Cannot get the toString of a null identity");
276336 }
277337 buffer.append(object.getClass().getName())
338 .append('@')
339 .append(Integer.toHexString(System.identityHashCode(object)));
340 }
341
342 /**
343 * <p>Appends the toString that would be produced by {@code Object}
344 * if a class did not override toString itself. {@code null}
345 * will throw a NullPointerException for either of the two parameters. </p>
346 *
347 * <pre>
348 * ObjectUtils.identityToString(builder, "") = builder.append("java.lang.String@1e23"
349 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa"
350 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa")
351 * </pre>
352 *
353 * @param builder the builder to append to
354 * @param object the object to create a toString for
355 * @since 3.2
356 */
357 public static void identityToString(final StringBuilder builder, final Object object) {
358 if (object == null) {
359 throw new NullPointerException("Cannot get the toString of a null identity");
360 }
361 builder.append(object.getClass().getName())
278362 .append('@')
279363 .append(Integer.toHexString(System.identityHashCode(object)));
280364 }
295379 * @see StringUtils#defaultString(String)
296380 * @see String#valueOf(Object)
297381 * @param obj the Object to {@code toString}, may be null
298 * @return the passed in Object's toString, or nullStr if {@code null} input
382 * @return the passed in Object's toString, or {@code ""} if {@code null} input
299383 * @since 2.0
300 */
301 public static String toString(Object obj) {
384 * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be
385 * removed in future releases. Note however that said method will return "null" for null references, while this
386 * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")}
387 */
388 @Deprecated
389 public static String toString(final Object obj) {
302390 return obj == null ? "" : obj.toString();
303391 }
304392
318406 * @see String#valueOf(Object)
319407 * @param obj the Object to {@code toString}, may be null
320408 * @param nullStr the String to return if {@code null} input, may be null
321 * @return the passed in Object's toString, or nullStr if {@code null} input
409 * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
322410 * @since 2.0
323 */
324 public static String toString(Object obj, String nullStr) {
411 * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and
412 * will be removed in future releases.
413 */
414 @Deprecated
415 public static String toString(final Object obj, final String nullStr) {
325416 return obj == null ? nullStr : obj.toString();
326417 }
327418
340431 * <li>If all the comparables are null, null is returned.
341432 * </ul>
342433 */
343 public static <T extends Comparable<? super T>> T min(T... values) {
434 public static <T extends Comparable<? super T>> T min(final T... values) {
344435 T result = null;
345436 if (values != null) {
346 for (T value : values) {
437 for (final T value : values) {
347438 if (compare(value, result, true) < 0) {
348439 result = value;
349440 }
365456 * <li>If all the comparables are null, null is returned.
366457 * </ul>
367458 */
368 public static <T extends Comparable<? super T>> T max(T... values) {
459 public static <T extends Comparable<? super T>> T max(final T... values) {
369460 T result = null;
370461 if (values != null) {
371 for (T value : values) {
462 for (final T value : values) {
372463 if (compare(value, result, false) > 0) {
373464 result = value;
374465 }
387478 * @return a negative value if c1 < c2, zero if c1 = c2
388479 * and a positive value if c1 > c2
389480 */
390 public static <T extends Comparable<? super T>> int compare(T c1, T c2) {
481 public static <T extends Comparable<? super T>> int compare(final T c1, final T c2) {
391482 return compare(c1, c2, false);
392483 }
393484
404495 * and a positive value if c1 > c2
405496 * @see java.util.Comparator#compare(Object, Object)
406497 */
407 public static <T extends Comparable<? super T>> int compare(T c1, T c2, boolean nullGreater) {
498 public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) {
408499 if (c1 == c2) {
409500 return 0;
410501 } else if (c1 == null) {
425516 * @throws IllegalArgumentException if items is empty or contains {@code null} values
426517 * @since 3.0.1
427518 */
428 public static <T extends Comparable<? super T>> T median(T... items) {
519 public static <T extends Comparable<? super T>> T median(final T... items) {
429520 Validate.notEmpty(items);
430521 Validate.noNullElements(items);
431 TreeSet<T> sort = new TreeSet<T>();
522 final TreeSet<T> sort = new TreeSet<T>();
432523 Collections.addAll(sort, items);
433524 @SuppressWarnings("unchecked") //we know all items added were T instances
525 final
434526 T result = (T) sort.toArray()[(sort.size() - 1) / 2];
435527 return result;
436528 }
446538 * @throws IllegalArgumentException if items is empty or contains {@code null} values
447539 * @since 3.0.1
448540 */
449 public static <T> T median(Comparator<T> comparator, T... items) {
541 public static <T> T median(final Comparator<T> comparator, final T... items) {
450542 Validate.notEmpty(items, "null/empty items");
451543 Validate.noNullElements(items);
452544 Validate.notNull(comparator, "null comparator");
453 TreeSet<T> sort = new TreeSet<T>(comparator);
545 final TreeSet<T> sort = new TreeSet<T>(comparator);
454546 Collections.addAll(sort, items);
455547 @SuppressWarnings("unchecked") //we know all items added were T instances
548 final
456549 T result = (T) sort.toArray()[(sort.size() - 1) / 2];
457550 return result;
458551 }
467560 * @return most populous T, {@code null} if non-unique or no items supplied
468561 * @since 3.0.1
469562 */
470 public static <T> T mode(T... items) {
563 public static <T> T mode(final T... items) {
471564 if (ArrayUtils.isNotEmpty(items)) {
472 HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(items.length);
473 for (T t : items) {
474 MutableInt count = occurrences.get(t);
565 final HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(items.length);
566 for (final T t : items) {
567 final MutableInt count = occurrences.get(t);
475568 if (count == null) {
476569 occurrences.put(t, new MutableInt(1));
477570 } else {
480573 }
481574 T result = null;
482575 int max = 0;
483 for (Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
484 int cmp = e.getValue().intValue();
576 for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
577 final int cmp = e.getValue().intValue();
485578 if (cmp == max) {
486579 result = null;
487580 } else if (cmp > max) {
535628 + obj.getClass().getName(), e.getCause());
536629 }
537630 }
538 @SuppressWarnings("unchecked")
631 @SuppressWarnings("unchecked") // OK because input is of type T
539632 final T checked = (T) result;
540633 return checked;
541634 }
604697 }
605698 }
606699
700
701 // Constants (LANG-816):
702 /*
703 These methods ensure constants are not inlined by javac.
704 For example, typically a developer might declare a constant like so:
705
706 public final static int MAGIC_NUMBER = 5;
707
708 Should a different jar file refer to this, and the MAGIC_NUMBER
709 is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar
710 file will need to recompile itself. This is because javac
711 typically inlines the primitive or String constant directly into
712 the bytecode, and removes the reference to the MAGIC_NUMBER field.
713
714 To help the other jar (so that it does not need to recompile
715 when constants are changed) the original developer can declare
716 their constant using one of the CONST() utility methods, instead:
717
718 public final static int MAGIC_NUMBER = CONST(5);
719 */
720
721
722 /**
723 * This method returns the provided value unchanged.
724 * This can prevent javac from inlining a constant
725 * field, e.g.,
726 *
727 * <pre>
728 * public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
729 * </pre>
730 *
731 * This way any jars that refer to this field do not
732 * have to recompile themselves if the field's value
733 * changes at some future date.
734 *
735 * @param v the boolean value to return
736 * @return the boolean v, unchanged
737 * @since 3.2
738 */
739 public static boolean CONST(final boolean v) { return v; }
740
741 /**
742 * This method returns the provided value unchanged.
743 * This can prevent javac from inlining a constant
744 * field, e.g.,
745 *
746 * <pre>
747 * public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
748 * </pre>
749 *
750 * This way any jars that refer to this field do not
751 * have to recompile themselves if the field's value
752 * changes at some future date.
753 *
754 * @param v the byte value to return
755 * @return the byte v, unchanged
756 * @since 3.2
757 */
758 public static byte CONST(final byte v) { return v; }
759
760 /**
761 * This method returns the provided value unchanged.
762 * This can prevent javac from inlining a constant
763 * field, e.g.,
764 *
765 * <pre>
766 * public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
767 * </pre>
768 *
769 * This way any jars that refer to this field do not
770 * have to recompile themselves if the field's value
771 * changes at some future date.
772 *
773 * @param v the byte literal (as an int) value to return
774 * @throws IllegalArgumentException if the value passed to v
775 * is larger than a byte, that is, smaller than -128 or
776 * larger than 127.
777 * @return the byte v, unchanged
778 * @since 3.2
779 */
780 public static byte CONST_BYTE(final int v) throws IllegalArgumentException {
781 if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) {
782 throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]");
783 }
784 return (byte) v;
785 }
786
787 /**
788 * This method returns the provided value unchanged.
789 * This can prevent javac from inlining a constant
790 * field, e.g.,
791 *
792 * <pre>
793 * public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
794 * </pre>
795 *
796 * This way any jars that refer to this field do not
797 * have to recompile themselves if the field's value
798 * changes at some future date.
799 *
800 * @param v the char value to return
801 * @return the char v, unchanged
802 * @since 3.2
803 */
804 public static char CONST(final char v) { return v; }
805
806 /**
807 * This method returns the provided value unchanged.
808 * This can prevent javac from inlining a constant
809 * field, e.g.,
810 *
811 * <pre>
812 * public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
813 * </pre>
814 *
815 * This way any jars that refer to this field do not
816 * have to recompile themselves if the field's value
817 * changes at some future date.
818 *
819 * @param v the short value to return
820 * @return the short v, unchanged
821 * @since 3.2
822 */
823 public static short CONST(final short v) { return v; }
824
825 /**
826 * This method returns the provided value unchanged.
827 * This can prevent javac from inlining a constant
828 * field, e.g.,
829 *
830 * <pre>
831 * public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
832 * </pre>
833 *
834 * This way any jars that refer to this field do not
835 * have to recompile themselves if the field's value
836 * changes at some future date.
837 *
838 * @param v the short literal (as an int) value to return
839 * @throws IllegalArgumentException if the value passed to v
840 * is larger than a short, that is, smaller than -32768 or
841 * larger than 32767.
842 * @return the byte v, unchanged
843 * @since 3.2
844 */
845 public static short CONST_SHORT(final int v) throws IllegalArgumentException {
846 if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) {
847 throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]");
848 }
849 return (short) v;
850 }
851
852
853 /**
854 * This method returns the provided value unchanged.
855 * This can prevent javac from inlining a constant
856 * field, e.g.,
857 *
858 * <pre>
859 * public final static int MAGIC_INT = ObjectUtils.CONST(123);
860 * </pre>
861 *
862 * This way any jars that refer to this field do not
863 * have to recompile themselves if the field's value
864 * changes at some future date.
865 *
866 * @param v the int value to return
867 * @return the int v, unchanged
868 * @since 3.2
869 */
870 public static int CONST(final int v) { return v; }
871
872 /**
873 * This method returns the provided value unchanged.
874 * This can prevent javac from inlining a constant
875 * field, e.g.,
876 *
877 * <pre>
878 * public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
879 * </pre>
880 *
881 * This way any jars that refer to this field do not
882 * have to recompile themselves if the field's value
883 * changes at some future date.
884 *
885 * @param v the long value to return
886 * @return the long v, unchanged
887 * @since 3.2
888 */
889 public static long CONST(final long v) { return v; }
890
891 /**
892 * This method returns the provided value unchanged.
893 * This can prevent javac from inlining a constant
894 * field, e.g.,
895 *
896 * <pre>
897 * public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
898 * </pre>
899 *
900 * This way any jars that refer to this field do not
901 * have to recompile themselves if the field's value
902 * changes at some future date.
903 *
904 * @param v the float value to return
905 * @return the float v, unchanged
906 * @since 3.2
907 */
908 public static float CONST(final float v) { return v; }
909
910 /**
911 * This method returns the provided value unchanged.
912 * This can prevent javac from inlining a constant
913 * field, e.g.,
914 *
915 * <pre>
916 * public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
917 * </pre>
918 *
919 * This way any jars that refer to this field do not
920 * have to recompile themselves if the field's value
921 * changes at some future date.
922 *
923 * @param v the double value to return
924 * @return the double v, unchanged
925 * @since 3.2
926 */
927 public static double CONST(final double v) { return v; }
928
929 /**
930 * This method returns the provided value unchanged.
931 * This can prevent javac from inlining a constant
932 * field, e.g.,
933 *
934 * <pre>
935 * public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
936 * </pre>
937 *
938 * This way any jars that refer to this field do not
939 * have to recompile themselves if the field's value
940 * changes at some future date.
941 *
942 * @param <T> the Object type
943 * @param v the genericized Object value to return (typically a String).
944 * @return the genericized Object v, unchanged (typically a String).
945 * @since 3.2
946 */
947 public static <T> T CONST(final T v) { return v; }
948
607949 }
3030 *
3131 * <p>#ThreadSafe#</p>
3232 * @since 1.0
33 * @version $Id: RandomStringUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
33 * @version $Id: RandomStringUtils.java 1532684 2013-10-16 08:28:42Z bayard $
3434 */
3535 public class RandomStringUtils {
3636
6464 * @param count the length of random string to create
6565 * @return the random string
6666 */
67 public static String random(int count) {
67 public static String random(final int count) {
6868 return random(count, false, false);
6969 }
7070
7878 * @param count the length of random string to create
7979 * @return the random string
8080 */
81 public static String randomAscii(int count) {
81 public static String randomAscii(final int count) {
8282 return random(count, 32, 127, false, false);
8383 }
8484
9292 * @param count the length of random string to create
9393 * @return the random string
9494 */
95 public static String randomAlphabetic(int count) {
95 public static String randomAlphabetic(final int count) {
9696 return random(count, true, false);
9797 }
9898
106106 * @param count the length of random string to create
107107 * @return the random string
108108 */
109 public static String randomAlphanumeric(int count) {
109 public static String randomAlphanumeric(final int count) {
110110 return random(count, true, true);
111111 }
112112
120120 * @param count the length of random string to create
121121 * @return the random string
122122 */
123 public static String randomNumeric(int count) {
123 public static String randomNumeric(final int count) {
124124 return random(count, false, true);
125125 }
126126
132132 * characters as indicated by the arguments.</p>
133133 *
134134 * @param count the length of random string to create
135 * @param letters if {@code true}, generated string will include
135 * @param letters if {@code true}, generated string may include
136136 * alphabetic characters
137 * @param numbers if {@code true}, generated string will include
137 * @param numbers if {@code true}, generated string may include
138138 * numeric characters
139139 * @return the random string
140140 */
141 public static String random(int count, boolean letters, boolean numbers) {
141 public static String random(final int count, final boolean letters, final boolean numbers) {
142142 return random(count, 0, 0, letters, numbers);
143143 }
144144
152152 * @param count the length of random string to create
153153 * @param start the position in set of chars to start at
154154 * @param end the position in set of chars to end before
155 * @param letters if {@code true}, generated string will include
155 * @param letters if {@code true}, generated string may include
156156 * alphabetic characters
157 * @param numbers if {@code true}, generated string will include
157 * @param numbers if {@code true}, generated string may include
158158 * numeric characters
159159 * @return the random string
160160 */
161 public static String random(int count, int start, int end, boolean letters, boolean numbers) {
161 public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers) {
162162 return random(count, start, end, letters, numbers, null, RANDOM);
163163 }
164164
182182 * @throws ArrayIndexOutOfBoundsException if there are not
183183 * {@code (end - start) + 1} characters in the set array.
184184 */
185 public static String random(int count, int start, int end, boolean letters, boolean numbers, char... chars) {
185 public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers, final char... chars) {
186186 return random(count, start, end, letters, numbers, chars, RANDOM);
187187 }
188188
210210 * @param end the position in set of chars to end before
211211 * @param letters only allow letters?
212212 * @param numbers only allow numbers?
213 * @param chars the set of chars to choose randoms from.
213 * @param chars the set of chars to choose randoms from, must not be empty.
214214 * If {@code null}, then it will use the set of all chars.
215215 * @param random a source of randomness.
216216 * @return the random string
217217 * @throws ArrayIndexOutOfBoundsException if there are not
218218 * {@code (end - start) + 1} characters in the set array.
219 * @throws IllegalArgumentException if {@code count} &lt; 0.
219 * @throws IllegalArgumentException if {@code count} &lt; 0 or the provided chars array is empty.
220220 * @since 2.0
221221 */
222 public static String random(int count, int start, int end, boolean letters, boolean numbers,
223 char[] chars, Random random) {
222 public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
223 final char[] chars, final Random random) {
224224 if (count == 0) {
225225 return "";
226226 } else if (count < 0) {
227227 throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
228228 }
229 if (chars != null && chars.length == 0) {
230 throw new IllegalArgumentException("The chars array must not be empty");
231 }
232
229233 if (start == 0 && end == 0) {
230 end = 'z' + 1;
231 start = ' ';
232 if (!letters && !numbers) {
233 start = 0;
234 end = Integer.MAX_VALUE;
234 if (chars != null) {
235 end = chars.length;
236 } else {
237 if (!letters && !numbers) {
238 end = Integer.MAX_VALUE;
239 } else {
240 end = 'z' + 1;
241 start = ' ';
242 }
235243 }
236 }
237
238 char[] buffer = new char[count];
239 int gap = end - start;
244 } else {
245 if (end <= start) {
246 throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
247 }
248 }
249
250 final char[] buffer = new char[count];
251 final int gap = end - start;
240252
241253 while (count-- != 0) {
242254 char ch;
284296 * specified.</p>
285297 *
286298 * <p>Characters will be chosen from the set of characters
287 * specified.</p>
299 * specified by the string, must not be empty.
300 * If null, the set of all characters is used.</p>
288301 *
289302 * @param count the length of random string to create
290303 * @param chars the String containing the set of characters to use,
291 * may be null
292 * @return the random string
293 * @throws IllegalArgumentException if {@code count} &lt; 0.
294 */
295 public static String random(int count, String chars) {
304 * may be null, but must not be empty
305 * @return the random string
306 * @throws IllegalArgumentException if {@code count} &lt; 0 or the string is empty.
307 */
308 public static String random(final int count, final String chars) {
296309 if (chars == null) {
297310 return random(count, 0, 0, false, false, null, RANDOM);
298311 }
311324 * @return the random string
312325 * @throws IllegalArgumentException if {@code count} &lt; 0.
313326 */
314 public static String random(int count, char... chars) {
327 public static String random(final int count, final char... chars) {
315328 if (chars == null) {
316329 return random(count, 0, 0, false, false, null, RANDOM);
317330 }
2727 * <p>#ThreadSafe# if the objects and comparator are thread-safe</p>
2828 *
2929 * @since 3.0
30 * @version $Id: Range.java 1199894 2011-11-09 17:53:59Z ggregory $
30 * @version $Id: Range.java 1436770 2013-01-22 07:09:45Z ggregory $
3131 */
3232 public final class Range<T> implements Serializable {
3333
7171 * @throws IllegalArgumentException if the element is null
7272 * @throws ClassCastException if the element is not {@code Comparable}
7373 */
74 public static <T extends Comparable<T>> Range<T> is(T element) {
74 public static <T extends Comparable<T>> Range<T> is(final T element) {
7575 return between(element, element, null);
7676 }
7777
8989 * @throws IllegalArgumentException if the element is null
9090 * @throws ClassCastException if using natural ordering and the elements are not {@code Comparable}
9191 */
92 public static <T> Range<T> is(T element, Comparator<T> comparator) {
92 public static <T> Range<T> is(final T element, final Comparator<T> comparator) {
9393 return between(element, element, comparator);
9494 }
9595
109109 * @throws IllegalArgumentException if either element is null
110110 * @throws ClassCastException if the elements are not {@code Comparable}
111111 */
112 public static <T extends Comparable<T>> Range<T> between(T fromInclusive, T toInclusive) {
112 public static <T extends Comparable<T>> Range<T> between(final T fromInclusive, final T toInclusive) {
113113 return between(fromInclusive, toInclusive, null);
114114 }
115115
130130 * @throws IllegalArgumentException if either element is null
131131 * @throws ClassCastException if using natural ordering and the elements are not {@code Comparable}
132132 */
133 public static <T> Range<T> between(T fromInclusive, T toInclusive, Comparator<T> comparator) {
133 public static <T> Range<T> between(final T fromInclusive, final T toInclusive, final Comparator<T> comparator) {
134134 return new Range<T>(fromInclusive, toInclusive, comparator);
135135 }
136136
142142 * @param comparator the comparator to be used, null for natural ordering
143143 */
144144 @SuppressWarnings("unchecked")
145 private Range(T element1, T element2, Comparator<T> comparator) {
145 private Range(final T element1, final T element2, Comparator<T> comparator) {
146146 if (element1 == null || element2 == null) {
147147 throw new IllegalArgumentException("Elements in a range must not be null: element1=" +
148148 element1 + ", element2=" + element2);
214214 * @param element the element to check for, null returns false
215215 * @return true if the specified element occurs within this range
216216 */
217 public boolean contains(T element) {
217 public boolean contains(final T element) {
218218 if (element == null) {
219219 return false;
220220 }
227227 * @param element the element to check for, null returns false
228228 * @return true if this range is entirely after the specified element
229229 */
230 public boolean isAfter(T element) {
230 public boolean isAfter(final T element) {
231231 if (element == null) {
232232 return false;
233233 }
240240 * @param element the element to check for, null returns false
241241 * @return true if the specified element occurs within this range
242242 */
243 public boolean isStartedBy(T element) {
243 public boolean isStartedBy(final T element) {
244244 if (element == null) {
245245 return false;
246246 }
253253 * @param element the element to check for, null returns false
254254 * @return true if the specified element occurs within this range
255255 */
256 public boolean isEndedBy(T element) {
256 public boolean isEndedBy(final T element) {
257257 if (element == null) {
258258 return false;
259259 }
266266 * @param element the element to check for, null returns false
267267 * @return true if this range is entirely before the specified element
268268 */
269 public boolean isBefore(T element) {
269 public boolean isBefore(final T element) {
270270 if (element == null) {
271271 return false;
272272 }
283283 * @param element the element to check for, not null
284284 * @return -1, 0 or +1 depending on the element's location relative to the range
285285 */
286 public int elementCompareTo(T element) {
286 public int elementCompareTo(final T element) {
287287 if (element == null) {
288288 // Comparable API says throw NPE on null
289289 throw new NullPointerException("Element is null");
309309 * @return true if this range contains the specified range
310310 * @throws RuntimeException if ranges cannot be compared
311311 */
312 public boolean containsRange(Range<T> otherRange) {
312 public boolean containsRange(final Range<T> otherRange) {
313313 if (otherRange == null) {
314314 return false;
315315 }
326326 * @return true if this range is completely after the specified range
327327 * @throws RuntimeException if ranges cannot be compared
328328 */
329 public boolean isAfterRange(Range<T> otherRange) {
329 public boolean isAfterRange(final Range<T> otherRange) {
330330 if (otherRange == null) {
331331 return false;
332332 }
345345 * range; otherwise, {@code false}
346346 * @throws RuntimeException if ranges cannot be compared
347347 */
348 public boolean isOverlappedBy(Range<T> otherRange) {
348 public boolean isOverlappedBy(final Range<T> otherRange) {
349349 if (otherRange == null) {
350350 return false;
351351 }
363363 * @return true if this range is completely before the specified range
364364 * @throws RuntimeException if ranges cannot be compared
365365 */
366 public boolean isBeforeRange(Range<T> otherRange) {
366 public boolean isBeforeRange(final Range<T> otherRange) {
367367 if (otherRange == null) {
368368 return false;
369369 }
377377 * @throws IllegalArgumentException if {@code other} does not overlap {@code this}
378378 * @since 3.0.1
379379 */
380 public Range<T> intersectionWith(Range<T> other) {
380 public Range<T> intersectionWith(final Range<T> other) {
381381 if (!this.isOverlappedBy(other)) {
382382 throw new IllegalArgumentException(String.format(
383383 "Cannot calculate intersection with non-overlapping range %s", other));
385385 if (this.equals(other)) {
386386 return this;
387387 }
388 T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum;
389 T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum;
388 final T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum;
389 final T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum;
390390 return between(min, max, getComparator());
391391 }
392392
403403 * @return true if this object is equal
404404 */
405405 @Override
406 public boolean equals(Object obj) {
406 public boolean equals(final Object obj) {
407407 if (obj == this) {
408408 return true;
409409 } else if (obj == null || obj.getClass() != getClass()) {
410410 return false;
411411 } else {
412412 @SuppressWarnings("unchecked") // OK because we checked the class above
413 final
413414 Range<T> range = (Range<T>) obj;
414415 return minimum.equals(range.minimum) &&
415416 maximum.equals(range.maximum);
445446 public String toString() {
446447 String result = toString;
447448 if (result == null) {
448 StringBuilder buf = new StringBuilder(32);
449 final StringBuilder buf = new StringBuilder(32);
449450 buf.append('[');
450451 buf.append(minimum);
451452 buf.append("..");
469470 * @param format the format string, optionally containing {@code %1$s}, {@code %2$s} and {@code %3$s}, not null
470471 * @return the formatted string, not null
471472 */
472 public String toString(String format) {
473 public String toString(final String format) {
473474 return String.format(format, minimum, maximum, comparator);
474475 }
475476
484485 * @param obj2 right hand side of comparison
485486 * @return negative, 0, positive comparison value
486487 */
487 public int compare(Object obj1, Object obj2) {
488 @Override
489 public int compare(final Object obj1, final Object obj2) {
488490 return ((Comparable) obj1).compareTo(obj2);
489491 }
490492 }
2020 *
2121 * <p>The original error is wrapped within this one.</p>
2222 *
23 * <p>#NotThreadSafe# because Throwable is not threadsafe</p>
23 * <p>#NotThreadSafe# because Throwable is not thread-safe</p>
2424 * @since 1.0
25 * @version $Id: SerializationException.java 1088899 2011-04-05 05:31:27Z bayard $
25 * @version $Id: SerializationException.java 1436768 2013-01-22 07:07:42Z ggregory $
2626 */
2727 public class SerializationException extends RuntimeException {
2828
4747 *
4848 * @param msg The error message.
4949 */
50 public SerializationException(String msg) {
50 public SerializationException(final String msg) {
5151 super(msg);
5252 }
5353
5858 * @param cause The {@code Exception} or {@code Error}
5959 * that caused this exception to be thrown.
6060 */
61 public SerializationException(Throwable cause) {
61 public SerializationException(final Throwable cause) {
6262 super(cause);
6363 }
6464
7070 * @param cause The {@code Exception} or {@code Error}
7171 * that caused this exception to be thrown.
7272 */
73 public SerializationException(String msg, Throwable cause) {
73 public SerializationException(final String msg, final Throwable cause) {
7474 super(msg, cause);
7575 }
7676
2424 import java.io.ObjectStreamClass;
2525 import java.io.OutputStream;
2626 import java.io.Serializable;
27 import java.util.HashMap;
28 import java.util.Map;
2729
2830 /**
2931 * <p>Assists with the serialization process and performs additional functionality based
4042 *
4143 * <p>#ThreadSafe#</p>
4244 * @since 1.0
43 * @version $Id: SerializationUtils.java 1199718 2011-11-09 12:43:20Z sebb $
45 * @version $Id: SerializationUtils.java 1478234 2013-05-01 23:43:35Z sebb $
4446 */
4547 public class SerializationUtils {
4648
7274 * @return the cloned object
7375 * @throws SerializationException (runtime) if the serialization fails
7476 */
75 public static <T extends Serializable> T clone(T object) {
77 public static <T extends Serializable> T clone(final T object) {
7678 if (object == null) {
7779 return null;
7880 }
79 byte[] objectData = serialize(object);
80 ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
81 final byte[] objectData = serialize(object);
82 final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
8183
8284 ClassLoaderAwareObjectInputStream in = null;
8385 try {
8991 * is of the same type as the original serialized object
9092 */
9193 @SuppressWarnings("unchecked") // see above
94 final
9295 T readObject = (T) in.readObject();
9396 return readObject;
9497
95 } catch (ClassNotFoundException ex) {
98 } catch (final ClassNotFoundException ex) {
9699 throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
97 } catch (IOException ex) {
100 } catch (final IOException ex) {
98101 throw new SerializationException("IOException while reading cloned object data", ex);
99102 } finally {
100103 try {
101104 if (in != null) {
102105 in.close();
103106 }
104 } catch (IOException ex) {
107 } catch (final IOException ex) {
105108 throw new SerializationException("IOException on closing cloned object data InputStream.", ex);
106109 }
107110 }
124127 * @throws IllegalArgumentException if {@code outputStream} is {@code null}
125128 * @throws SerializationException (runtime) if the serialization fails
126129 */
127 public static void serialize(Serializable obj, OutputStream outputStream) {
130 public static void serialize(final Serializable obj, final OutputStream outputStream) {
128131 if (outputStream == null) {
129132 throw new IllegalArgumentException("The OutputStream must not be null");
130133 }
134137 out = new ObjectOutputStream(outputStream);
135138 out.writeObject(obj);
136139
137 } catch (IOException ex) {
140 } catch (final IOException ex) {
138141 throw new SerializationException(ex);
139142 } finally {
140143 try {
141144 if (out != null) {
142145 out.close();
143146 }
144 } catch (IOException ex) { // NOPMD
147 } catch (final IOException ex) { // NOPMD
145148 // ignore close exception
146149 }
147150 }
155158 * @return a byte[] with the converted Serializable
156159 * @throws SerializationException (runtime) if the serialization fails
157160 */
158 public static byte[] serialize(Serializable obj) {
159 ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
161 public static byte[] serialize(final Serializable obj) {
162 final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
160163 serialize(obj, baos);
161164 return baos.toByteArray();
162165 }
164167 // Deserialize
165168 //-----------------------------------------------------------------------
166169 /**
167 * <p>Deserializes an {@code Object} from the specified stream.</p>
168 *
169 * <p>The stream will be closed once the object is written. This
170 * avoids the need for a finally clause, and maybe also exception
171 * handling, in the application code.</p>
172 *
173 * <p>The stream passed in is not buffered internally within this method.
174 * This is the responsibility of your application if desired.</p>
175 *
176 * @param inputStream the serialized object input stream, must not be null
170 * <p>
171 * Deserializes an {@code Object} from the specified stream.
172 * </p>
173 *
174 * <p>
175 * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
176 * exception handling, in the application code.
177 * </p>
178 *
179 * <p>
180 * The stream passed in is not buffered internally within this method. This is the responsibility of your
181 * application if desired.
182 * </p>
183 *
184 * <p>
185 * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
186 * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
187 * Note that in both cases, the ClassCastException is in the call site, not in this method.
188 * </p>
189 *
190 * @param <T> the object type to be deserialized
191 * @param inputStream
192 * the serialized object input stream, must not be null
177193 * @return the deserialized object
178 * @throws IllegalArgumentException if {@code inputStream} is {@code null}
179 * @throws SerializationException (runtime) if the serialization fails
180 */
181 public static Object deserialize(InputStream inputStream) {
194 * @throws IllegalArgumentException
195 * if {@code inputStream} is {@code null}
196 * @throws SerializationException
197 * (runtime) if the serialization fails
198 */
199 public static <T> T deserialize(final InputStream inputStream) {
182200 if (inputStream == null) {
183201 throw new IllegalArgumentException("The InputStream must not be null");
184202 }
186204 try {
187205 // stream closed in the finally
188206 in = new ObjectInputStream(inputStream);
189 return in.readObject();
190
191 } catch (ClassNotFoundException ex) {
207 @SuppressWarnings("unchecked") // may fail with CCE if serialised form is incorrect
208 final T obj = (T) in.readObject();
209 return obj;
210
211 } catch (final ClassCastException ex) {
192212 throw new SerializationException(ex);
193 } catch (IOException ex) {
213 } catch (final ClassNotFoundException ex) {
214 throw new SerializationException(ex);
215 } catch (final IOException ex) {
194216 throw new SerializationException(ex);
195217 } finally {
196218 try {
197219 if (in != null) {
198220 in.close();
199221 }
200 } catch (IOException ex) { // NOPMD
222 } catch (final IOException ex) { // NOPMD
201223 // ignore close exception
202224 }
203225 }
204226 }
205227
206228 /**
207 * <p>Deserializes a single {@code Object} from an array of bytes.</p>
208 *
209 * @param objectData the serialized object, must not be null
229 * <p>
230 * Deserializes a single {@code Object} from an array of bytes.
231 * </p>
232 *
233 * <p>
234 * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
235 * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
236 * Note that in both cases, the ClassCastException is in the call site, not in this method.
237 * </p>
238 *
239 * @param <T> the object type to be deserialized
240 * @param objectData
241 * the serialized object, must not be null
210242 * @return the deserialized object
211 * @throws IllegalArgumentException if {@code objectData} is {@code null}
212 * @throws SerializationException (runtime) if the serialization fails
213 */
214 public static Object deserialize(byte[] objectData) {
243 * @throws IllegalArgumentException
244 * if {@code objectData} is {@code null}
245 * @throws SerializationException
246 * (runtime) if the serialization fails
247 */
248 public static <T> T deserialize(final byte[] objectData) {
215249 if (objectData == null) {
216250 throw new IllegalArgumentException("The byte[] must not be null");
217251 }
218 ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
219 return deserialize(bais);
252 return SerializationUtils.<T>deserialize(new ByteArrayInputStream(objectData));
220253 }
221254
222255 /**
233266 * class here is a workaround, see the JIRA issue LANG-626. </p>
234267 */
235268 static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
236 private ClassLoader classLoader;
237
269 private static final Map<String, Class<?>> primitiveTypes =
270 new HashMap<String, Class<?>>();
271 private final ClassLoader classLoader;
272
238273 /**
239274 * Constructor.
240275 * @param in The <code>InputStream</code>.
242277 * @throws IOException if an I/O error occurs while reading stream header.
243278 * @see java.io.ObjectInputStream
244279 */
245 public ClassLoaderAwareObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
280 public ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
246281 super(in);
247282 this.classLoader = classLoader;
283
284 primitiveTypes.put("byte", byte.class);
285 primitiveTypes.put("short", short.class);
286 primitiveTypes.put("int", int.class);
287 primitiveTypes.put("long", long.class);
288 primitiveTypes.put("float", float.class);
289 primitiveTypes.put("double", double.class);
290 primitiveTypes.put("boolean", boolean.class);
291 primitiveTypes.put("char", char.class);
292 primitiveTypes.put("void", void.class);
248293 }
249294
250295 /**
256301 * @throws ClassNotFoundException If class of a serialized object cannot be found.
257302 */
258303 @Override
259 protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
260 String name = desc.getName();
304 protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
305 final String name = desc.getName();
261306 try {
262307 return Class.forName(name, false, classLoader);
263 } catch (ClassNotFoundException ex) {
264 return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
308 } catch (final ClassNotFoundException ex) {
309 try {
310 return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
311 } catch (final ClassNotFoundException cnfe) {
312 final Class<?> cls = primitiveTypes.get(name);
313 if (cls != null) {
314 return cls;
315 } else {
316 throw cnfe;
317 }
318 }
265319 }
266320 }
267321
2121 import org.apache.commons.lang3.text.translate.AggregateTranslator;
2222 import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
2323 import org.apache.commons.lang3.text.translate.EntityArrays;
24 import org.apache.commons.lang3.text.translate.JavaUnicodeEscaper;
2425 import org.apache.commons.lang3.text.translate.LookupTranslator;
2526 import org.apache.commons.lang3.text.translate.NumericEntityUnescaper;
2627 import org.apache.commons.lang3.text.translate.OctalUnescaper;
27 import org.apache.commons.lang3.text.translate.UnicodeEscaper;
2828 import org.apache.commons.lang3.text.translate.UnicodeUnescaper;
2929
3030 /**
3333 *
3434 * <p>#ThreadSafe#</p>
3535 * @since 2.0
36 * @version $Id: StringEscapeUtils.java 1148520 2011-07-19 20:53:23Z ggregory $
36 * @version $Id: StringEscapeUtils.java 1467206 2013-04-12 08:39:02Z bayard $
3737 */
3838 public class StringEscapeUtils {
3939
5656 }).with(
5757 new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE())
5858 ).with(
59 UnicodeEscaper.outsideOf(32, 0x7f)
59 JavaUnicodeEscaper.outsideOf(32, 0x7f)
6060 );
6161
6262 /**
7878 {"/", "\\/"}
7979 }),
8080 new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()),
81 UnicodeEscaper.outsideOf(32, 0x7f)
82 );
83
81 JavaUnicodeEscaper.outsideOf(32, 0x7f)
82 );
83
84 /**
85 * Translator object for escaping Json.
86 *
87 * While {@link #escapeJson(String)} is the expected method of use, this
88 * object allows the Json escaping functionality to be used
89 * as the foundation for a custom translator.
90 *
91 * @since 3.2
92 */
93 public static final CharSequenceTranslator ESCAPE_JSON =
94 new AggregateTranslator(
95 new LookupTranslator(
96 new String[][] {
97 {"\"", "\\\""},
98 {"\\", "\\\\"},
99 {"/", "\\/"}
100 }),
101 new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()),
102 JavaUnicodeEscaper.outsideOf(32, 0x7f)
103 );
104
84105 /**
85106 * Translator object for escaping XML.
86107 *
150171 new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
151172
152173 @Override
153 public int translate(CharSequence input, int index, Writer out) throws IOException {
174 public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
154175
155176 if(index != 0) {
156177 throw new IllegalStateException("CsvEscaper should never reach the [1] index");
205226 public static final CharSequenceTranslator UNESCAPE_ECMASCRIPT = UNESCAPE_JAVA;
206227
207228 /**
229 * Translator object for unescaping escaped Json.
230 *
231 * While {@link #unescapeJson(String)} is the expected method of use, this
232 * object allows the Json unescaping functionality to be used
233 * as the foundation for a custom translator.
234 *
235 * @since 3.2
236 */
237 public static final CharSequenceTranslator UNESCAPE_JSON = UNESCAPE_JAVA;
238
239 /**
208240 * Translator object for unescaping escaped HTML 3.0.
209241 *
210242 * While {@link #unescapeHtml3(String)} is the expected method of use, this
273305 new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
274306
275307 @Override
276 public int translate(CharSequence input, int index, Writer out) throws IOException {
308 public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
277309
278310 if(index != 0) {
279311 throw new IllegalStateException("CsvUnescaper should never reach the [1] index");
285317 }
286318
287319 // strip quotes
288 String quoteless = input.subSequence(1, input.length() - 1).toString();
320 final String quoteless = input.subSequence(1, input.length() - 1).toString();
289321
290322 if ( StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS) ) {
291323 // deal with escaped quotes; ie) ""
336368 * @param input String to escape values in, may be null
337369 * @return String with escaped values, {@code null} if null string input
338370 */
339 public static final String escapeJava(String input) {
371 public static final String escapeJava(final String input) {
340372 return ESCAPE_JAVA.translate(input);
341373 }
342374
365397 *
366398 * @since 3.0
367399 */
368 public static final String escapeEcmaScript(String input) {
400 public static final String escapeEcmaScript(final String input) {
369401 return ESCAPE_ECMASCRIPT.translate(input);
402 }
403
404 /**
405 * <p>Escapes the characters in a {@code String} using Json String rules.</p>
406 * <p>Escapes any values it finds into their Json String form.
407 * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
408 *
409 * <p>So a tab becomes the characters {@code '\\'} and
410 * {@code 't'}.</p>
411 *
412 * <p>The only difference between Java strings and Json strings
413 * is that in Json, forward-slash (/) is escaped.</p>
414 *
415 * <p>See http://www.ietf.org/rfc/rfc4627.txt for further details. </p>
416 *
417 * <p>Example:
418 * <pre>
419 * input string: He didn't say, "Stop!"
420 * output string: He didn't say, \"Stop!\"
421 * </pre>
422 * </p>
423 *
424 * @param input String to escape values in, may be null
425 * @return String with escaped values, {@code null} if null string input
426 *
427 * @since 3.2
428 */
429 public static final String escapeJson(final String input) {
430 return ESCAPE_JSON.translate(input);
370431 }
371432
372433 /**
378439 * @param input the {@code String} to unescape, may be null
379440 * @return a new unescaped {@code String}, {@code null} if null string input
380441 */
381 public static final String unescapeJava(String input) {
442 public static final String unescapeJava(final String input) {
382443 return UNESCAPE_JAVA.translate(input);
383444 }
384445
395456 *
396457 * @since 3.0
397458 */
398 public static final String unescapeEcmaScript(String input) {
459 public static final String unescapeEcmaScript(final String input) {
399460 return UNESCAPE_ECMASCRIPT.translate(input);
461 }
462
463 /**
464 * <p>Unescapes any Json literals found in the {@code String}.</p>
465 *
466 * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
467 * into a newline character, unless the {@code '\'} is preceded by another
468 * {@code '\'}.</p>
469 *
470 * @see #unescapeJava(String)
471 * @param input the {@code String} to unescape, may be null
472 * @return A new unescaped {@code String}, {@code null} if null string input
473 *
474 * @since 3.2
475 */
476 public static final String unescapeJson(final String input) {
477 return UNESCAPE_JSON.translate(input);
400478 }
401479
402480 // HTML and XML
428506 *
429507 * @since 3.0
430508 */
431 public static final String escapeHtml4(String input) {
509 public static final String escapeHtml4(final String input) {
432510 return ESCAPE_HTML4.translate(input);
433511 }
434512
441519 *
442520 * @since 3.0
443521 */
444 public static final String escapeHtml3(String input) {
522 public static final String escapeHtml3(final String input) {
445523 return ESCAPE_HTML3.translate(input);
446524 }
447525
463541 *
464542 * @since 3.0
465543 */
466 public static final String unescapeHtml4(String input) {
544 public static final String unescapeHtml4(final String input) {
467545 return UNESCAPE_HTML4.translate(input);
468546 }
469547
477555 *
478556 * @since 3.0
479557 */
480 public static final String unescapeHtml3(String input) {
558 public static final String unescapeHtml3(final String input) {
481559 return UNESCAPE_HTML3.translate(input);
482560 }
483561
501579 * @return a new escaped {@code String}, {@code null} if null string input
502580 * @see #unescapeXml(java.lang.String)
503581 */
504 public static final String escapeXml(String input) {
582 public static final String escapeXml(final String input) {
505583 return ESCAPE_XML.translate(input);
506584 }
507585
522600 * @return a new unescaped {@code String}, {@code null} if null string input
523601 * @see #escapeXml(String)
524602 */
525 public static final String unescapeXml(String input) {
603 public static final String unescapeXml(final String input) {
526604 return UNESCAPE_XML.translate(input);
527605 }
528606
551629 * newline or double quote, {@code null} if null string input
552630 * @since 2.4
553631 */
554 public static final String escapeCsv(String input) {
632 public static final String escapeCsv(final String input) {
555633 return ESCAPE_CSV.translate(input);
556634 }
557635
577655 * quotes unescaped, {@code null} if null string input
578656 * @since 2.4
579657 */
580 public static final String unescapeCsv(String input) {
658 public static final String unescapeCsv(final String input) {
581659 return UNESCAPE_CSV.translate(input);
582660 }
583661
1616 package org.apache.commons.lang3;
1717
1818 import java.io.UnsupportedEncodingException;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
19 import java.nio.charset.Charset;
20 import java.text.Normalizer;
2121 import java.util.ArrayList;
2222 import java.util.Arrays;
2323 import java.util.Iterator;
5858 * - Searches a String and replaces one String with another</li>
5959 * <li><b>Chomp/Chop</b>
6060 * - removes the last part of a String</li>
61 * <li><b>AppendIfMissing</b>
62 * - appends a suffix to the end of the String if not present</li>
63 * <li><b>PrependIfMissing</b>
64 * - prepends a prefix to the start of the String if not present</li>
6165 * <li><b>LeftPad/RightPad/Center/Repeat</b>
6266 * - pads a String</li>
6367 * <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
104108 * <p>#ThreadSafe#</p>
105109 * @see java.lang.String
106110 * @since 1.0
107 * @version $Id: StringUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
111 * @version $Id: StringUtils.java 1553928 2013-12-28 21:18:46Z ggregory $
108112 */
109113 //@Immutable
110114 public class StringUtils {
125129 // (not sure who tested this)
126130
127131 /**
132 * A String for a space character.
133 *
134 * @since 3.2
135 */
136 public static final String SPACE = " ";
137
138 /**
128139 * The empty String {@code ""}.
129140 * @since 2.0
130141 */
131142 public static final String EMPTY = "";
132143
133144 /**
145 * A String for linefeed LF ("\n").
146 *
147 * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
148 * for Character and String Literals</a>
149 * @since 3.2
150 */
151 public static final String LF = "\n";
152
153 /**
154 * A String for carriage return CR ("\r").
155 *
156 * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
157 * for Character and String Literals</a>
158 * @since 3.2
159 */
160 public static final String CR = "\r";
161
162 /**
134163 * Represents a failed index search.
135164 * @since 2.1
136165 */
143172
144173 /**
145174 * A regex pattern for recognizing blocks of whitespace characters.
146 */
147 private static final Pattern WHITESPACE_BLOCK = Pattern.compile("\\s+");
175 * The apparent convolutedness of the pattern serves the purpose of
176 * ignoring "blocks" consisting of only a single space: the pattern
177 * is used only to normalize whitespace, condensing "blocks" down to a
178 * single space, thus matching the same would likely cause a great
179 * many noop replacements.
180 */
181 private static final Pattern WHITESPACE_PATTERN = Pattern.compile("(?: |\\u00A0|\\s|[\\s&&[^ ]])\\s*");
148182
149183 /**
150184 * <p>{@code StringUtils} instances should NOT be constructed in
179213 * @return {@code true} if the CharSequence is empty or null
180214 * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
181215 */
182 public static boolean isEmpty(CharSequence cs) {
216 public static boolean isEmpty(final CharSequence cs) {
183217 return cs == null || cs.length() == 0;
184218 }
185219
198232 * @return {@code true} if the CharSequence is not empty and not null
199233 * @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
200234 */
201 public static boolean isNotEmpty(CharSequence cs) {
235 public static boolean isNotEmpty(final CharSequence cs) {
202236 return !StringUtils.isEmpty(cs);
203237 }
204
238
239 /**
240 * <p>Checks if any one of the CharSequences are empty ("") or null.</p>
241 *
242 * <pre>
243 * StringUtils.isAnyEmpty(null) = true
244 * StringUtils.isAnyEmpty(null, "foo") = true
245 * StringUtils.isAnyEmpty("", "bar") = true
246 * StringUtils.isAnyEmpty("bob", "") = true
247 * StringUtils.isAnyEmpty(" bob ", null) = true
248 * StringUtils.isAnyEmpty(" ", "bar") = false
249 * StringUtils.isAnyEmpty("foo", "bar") = false
250 * </pre>
251 *
252 * @param css the CharSequences to check, may be null or empty
253 * @return {@code true} if any of the CharSequences are empty or null
254 * @since 3.2
255 */
256 public static boolean isAnyEmpty(CharSequence... css) {
257 if (ArrayUtils.isEmpty(css)) {
258 return true;
259 }
260 for (CharSequence cs : css){
261 if (isEmpty(cs)) {
262 return true;
263 }
264 }
265 return false;
266 }
267
268 /**
269 * <p>Checks if none of the CharSequences are empty ("") or null.</p>
270 *
271 * <pre>
272 * StringUtils.isNoneEmpty(null) = false
273 * StringUtils.isNoneEmpty(null, "foo") = false
274 * StringUtils.isNoneEmpty("", "bar") = false
275 * StringUtils.isNoneEmpty("bob", "") = false
276 * StringUtils.isNoneEmpty(" bob ", null) = false
277 * StringUtils.isNoneEmpty(" ", "bar") = true
278 * StringUtils.isNoneEmpty("foo", "bar") = true
279 * </pre>
280 *
281 * @param css the CharSequences to check, may be null or empty
282 * @return {@code true} if none of the CharSequences are empty or null
283 * @since 3.2
284 */
285 public static boolean isNoneEmpty(CharSequence... css) {
286 return !isAnyEmpty(css);
287 }
205288 /**
206289 * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
207290 *
218301 * @since 2.0
219302 * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
220303 */
221 public static boolean isBlank(CharSequence cs) {
304 public static boolean isBlank(final CharSequence cs) {
222305 int strLen;
223306 if (cs == null || (strLen = cs.length()) == 0) {
224307 return true;
248331 * @since 2.0
249332 * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
250333 */
251 public static boolean isNotBlank(CharSequence cs) {
334 public static boolean isNotBlank(final CharSequence cs) {
252335 return !StringUtils.isBlank(cs);
336 }
337
338 /**
339 * <p>Checks if any one of the CharSequences are blank ("") or null and not whitespace only..</p>
340 *
341 * <pre>
342 * StringUtils.isAnyBlank(null) = true
343 * StringUtils.isAnyBlank(null, "foo") = true
344 * StringUtils.isAnyBlank(null, null) = true
345 * StringUtils.isAnyBlank("", "bar") = true
346 * StringUtils.isAnyBlank("bob", "") = true
347 * StringUtils.isAnyBlank(" bob ", null) = true
348 * StringUtils.isAnyBlank(" ", "bar") = true
349 * StringUtils.isAnyBlank("foo", "bar") = false
350 * </pre>
351 *
352 * @param css the CharSequences to check, may be null or empty
353 * @return {@code true} if any of the CharSequences are blank or null or whitespace only
354 * @since 3.2
355 */
356 public static boolean isAnyBlank(CharSequence... css) {
357 if (ArrayUtils.isEmpty(css)) {
358 return true;
359 }
360 for (CharSequence cs : css){
361 if (isBlank(cs)) {
362 return true;
363 }
364 }
365 return false;
366 }
367
368 /**
369 * <p>Checks if none of the CharSequences are blank ("") or null and whitespace only..</p>
370 *
371 * <pre>
372 * StringUtils.isNoneBlank(null) = false
373 * StringUtils.isNoneBlank(null, "foo") = false
374 * StringUtils.isNoneBlank(null, null) = false
375 * StringUtils.isNoneBlank("", "bar") = false
376 * StringUtils.isNoneBlank("bob", "") = false
377 * StringUtils.isNoneBlank(" bob ", null) = false
378 * StringUtils.isNoneBlank(" ", "bar") = false
379 * StringUtils.isNoneBlank("foo", "bar") = true
380 * </pre>
381 *
382 * @param css the CharSequences to check, may be null or empty
383 * @return {@code true} if none of the CharSequences are blank or null or whitespace only
384 * @since 3.2
385 */
386 public static boolean isNoneBlank(CharSequence... css) {
387 return !isAnyBlank(css);
253388 }
254389
255390 // Trim
277412 * @param str the String to be trimmed, may be null
278413 * @return the trimmed string, {@code null} if null String input
279414 */
280 public static String trim(String str) {
415 public static String trim(final String str) {
281416 return str == null ? null : str.trim();
282417 }
283418
303438 * {@code null} if only chars &lt;= 32, empty or null String input
304439 * @since 2.0
305440 */
306 public static String trimToNull(String str) {
307 String ts = trim(str);
441 public static String trimToNull(final String str) {
442 final String ts = trim(str);
308443 return isEmpty(ts) ? null : ts;
309444 }
310445
329464 * @return the trimmed String, or an empty String if {@code null} input
330465 * @since 2.0
331466 */
332 public static String trimToEmpty(String str) {
467 public static String trimToEmpty(final String str) {
333468 return str == null ? EMPTY : str.trim();
334469 }
335470
357492 * @param str the String to remove whitespace from, may be null
358493 * @return the stripped String, {@code null} if null String input
359494 */
360 public static String strip(String str) {
495 public static String strip(final String str) {
361496 return strip(str, null);
362497 }
363498
389524 return null;
390525 }
391526 str = strip(str, null);
392 return str.length() == 0 ? null : str;
527 return str.isEmpty() ? null : str;
393528 }
394529
395530 /**
414549 * @return the trimmed String, or an empty String if {@code null} input
415550 * @since 2.0
416551 */
417 public static String stripToEmpty(String str) {
552 public static String stripToEmpty(final String str) {
418553 return str == null ? EMPTY : strip(str, null);
419554 }
420555
444579 * @param stripChars the characters to remove, null treated as whitespace
445580 * @return the stripped String, {@code null} if null String input
446581 */
447 public static String strip(String str, String stripChars) {
582 public static String strip(String str, final String stripChars) {
448583 if (isEmpty(str)) {
449584 return str;
450585 }
476611 * @param stripChars the characters to remove, null treated as whitespace
477612 * @return the stripped String, {@code null} if null String input
478613 */
479 public static String stripStart(String str, String stripChars) {
614 public static String stripStart(final String str, final String stripChars) {
480615 int strLen;
481616 if (str == null || (strLen = str.length()) == 0) {
482617 return str;
486621 while (start != strLen && Character.isWhitespace(str.charAt(start))) {
487622 start++;
488623 }
489 } else if (stripChars.length() == 0) {
624 } else if (stripChars.isEmpty()) {
490625 return str;
491626 } else {
492627 while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) {
521656 * @param stripChars the set of characters to remove, null treated as whitespace
522657 * @return the stripped String, {@code null} if null String input
523658 */
524 public static String stripEnd(String str, String stripChars) {
659 public static String stripEnd(final String str, final String stripChars) {
525660 int end;
526661 if (str == null || (end = str.length()) == 0) {
527662 return str;
531666 while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
532667 end--;
533668 }
534 } else if (stripChars.length() == 0) {
669 } else if (stripChars.isEmpty()) {
535670 return str;
536671 } else {
537672 while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
562697 * @param strs the array to remove whitespace from, may be null
563698 * @return the stripped Strings, {@code null} if null array input
564699 */
565 public static String[] stripAll(String... strs) {
700 public static String[] stripAll(final String... strs) {
566701 return stripAll(strs, null);
567702 }
568703
591726 * @param stripChars the characters to remove, null treated as whitespace
592727 * @return the stripped Strings, {@code null} if null array input
593728 */
594 public static String[] stripAll(String[] strs, String stripChars) {
729 public static String[] stripAll(final String[] strs, final String stripChars) {
595730 int strsLen;
596731 if (strs == null || (strsLen = strs.length) == 0) {
597732 return strs;
598733 }
599 String[] newArr = new String[strsLen];
734 final String[] newArr = new String[strsLen];
600735 for (int i = 0; i < strsLen; i++) {
601736 newArr[i] = strip(strs[i], stripChars);
602737 }
607742 * <p>Removes diacritics (~= accents) from a string. The case will not be altered.</p>
608743 * <p>For instance, '&agrave;' will be replaced by 'a'.</p>
609744 * <p>Note that ligatures will be left as is.</p>
610 *
611 * <p>This method will use the first available implementation of:
612 * Java 6's {@link java.text.Normalizer}, Java 1.3&ndash;1.5's {@code sun.text.Normalizer}</p>
613745 *
614746 * <pre>
615747 * StringUtils.stripAccents(null) = null
624756 * @since 3.0
625757 */
626758 // See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907).
627 public static String stripAccents(String input) {
759 public static String stripAccents(final String input) {
628760 if(input == null) {
629761 return null;
630762 }
631 try {
632 String result = null;
633 if (InitStripAccents.java6NormalizeMethod != null) {
634 result = removeAccentsJava6(input);
635 } else if (InitStripAccents.sunDecomposeMethod != null) {
636 result = removeAccentsSUN(input);
637 } else {
638 throw new UnsupportedOperationException(
639 "The stripAccents(CharSequence) method requires at least"
640 +" Java6, but got: "+InitStripAccents.java6Exception
641 +"; or a Sun JVM: "+InitStripAccents.sunException);
642 }
643 // Note that none of the above methods correctly remove ligatures...
644 return result;
645 } catch(IllegalArgumentException iae) {
646 throw new RuntimeException("IllegalArgumentException occurred", iae);
647 } catch(IllegalAccessException iae) {
648 throw new RuntimeException("IllegalAccessException occurred", iae);
649 } catch(InvocationTargetException ite) {
650 throw new RuntimeException("InvocationTargetException occurred", ite);
651 } catch(SecurityException se) {
652 throw new RuntimeException("SecurityException occurred", se);
653 }
654 }
655
656 /**
657 * Use {@code java.text.Normalizer#normalize(CharSequence, Normalizer.Form)}
658 * (but be careful, this class exists in Java 1.3, with an entirely different meaning!)
659 *
660 * @param text the text to be processed
661 * @return the processed string
662 * @throws IllegalAccessException may be thrown by a reflection call
663 * @throws InvocationTargetException if a reflection call throws an exception
664 * @throws IllegalStateException if the {@code Normalizer} class is not available
665 */
666 private static String removeAccentsJava6(CharSequence text)
667 throws IllegalAccessException, InvocationTargetException {
668 /*
669 String decomposed = java.text.Normalizer.normalize(CharSequence, Normalizer.Form.NFD);
670 return java6Pattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$
671 */
672 if (InitStripAccents.java6NormalizeMethod == null || InitStripAccents.java6NormalizerFormNFD == null) {
673 throw new IllegalStateException("java.text.Normalizer is not available", InitStripAccents.java6Exception);
674 }
675 String result;
676 result = (String) InitStripAccents.java6NormalizeMethod.invoke(null, new Object[] {text, InitStripAccents.java6NormalizerFormNFD});
677 result = InitStripAccents.java6Pattern.matcher(result).replaceAll("");//$NON-NLS-1$
678 return result;
679 }
680
681 /**
682 * Use {@code sun.text.Normalizer#decompose(String, boolean, int)}
683 *
684 * @param text the text to be processed
685 * @return the processed string
686 * @throws IllegalAccessException may be thrown by a reflection call
687 * @throws InvocationTargetException if a reflection call throws an exception
688 * @throws IllegalStateException if the {@code Normalizer} class is not available
689 */
690 private static String removeAccentsSUN(CharSequence text)
691 throws IllegalAccessException, InvocationTargetException {
692 /*
693 String decomposed = sun.text.Normalizer.decompose(text, false, 0);
694 return sunPattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$
695 */
696 if (InitStripAccents.sunDecomposeMethod == null) {
697 throw new IllegalStateException("sun.text.Normalizer is not available", InitStripAccents.sunException);
698 }
699 String result;
700 result = (String) InitStripAccents.sunDecomposeMethod.invoke(null, new Object[] {text, Boolean.FALSE, Integer.valueOf(0)});
701 result = InitStripAccents.sunPattern.matcher(result).replaceAll("");//$NON-NLS-1$
702 return result;
703 }
704
705 // IOD container for stripAccent() initialisation
706 private static class InitStripAccents {
707 // SUN internal, Java 1.3 -> Java 5
708 private static final Throwable sunException;
709 private static final Method sunDecomposeMethod;
710 private static final Pattern sunPattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");//$NON-NLS-1$
711 // Java 6+
712 private static final Throwable java6Exception;
713 private static final Method java6NormalizeMethod;
714 private static final Object java6NormalizerFormNFD;
715 private static final Pattern java6Pattern = sunPattern;
716
717 static {
718 // Set up defaults for final static fields
719 Object _java6NormalizerFormNFD = null;
720 Method _java6NormalizeMethod = null;
721 Method _sunDecomposeMethod = null;
722 Throwable _java6Exception = null;
723 Throwable _sunException = null;
724 try {
725 // java.text.Normalizer.normalize(CharSequence, Normalizer.Form.NFD);
726 // Be careful not to get Java 1.3 java.text.Normalizer!
727 Class<?> normalizerFormClass = Thread.currentThread().getContextClassLoader()
728 .loadClass("java.text.Normalizer$Form");//$NON-NLS-1$
729 _java6NormalizerFormNFD = normalizerFormClass.getField("NFD").get(null);//$NON-NLS-1$
730 Class<?> normalizerClass = Thread.currentThread().getContextClassLoader()
731 .loadClass("java.text.Normalizer");//$NON-NLS-1$
732 _java6NormalizeMethod = normalizerClass.getMethod("normalize",//$NON-NLS-1$
733 new Class[] {CharSequence.class, normalizerFormClass});//$NON-NLS-1$
734 } catch (Exception e1) {
735 // Only check for Sun method if Java 6 method is not available
736 _java6Exception = e1;
737 try {
738 // sun.text.Normalizer.decompose(text, false, 0);
739 Class<?> normalizerClass = Thread.currentThread().getContextClassLoader()
740 .loadClass("sun.text.Normalizer");//$NON-NLS-1$
741 _sunDecomposeMethod = normalizerClass.getMethod("decompose",//$NON-NLS-1$
742 new Class[] {String.class, Boolean.TYPE, Integer.TYPE});//$NON-NLS-1$
743 } catch (Exception e2) {
744 _sunException = e2;
745 }
746 }
747
748 // Set up final static fields
749 java6Exception = _java6Exception;
750 java6NormalizerFormNFD = _java6NormalizerFormNFD;
751 java6NormalizeMethod = _java6NormalizeMethod;
752 sunException = _sunException;
753 sunDecomposeMethod = _sunDecomposeMethod;
754 }
763 final Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");//$NON-NLS-1$
764 final String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD);
765 // Note that this doesn't correctly remove ligatures...
766 return pattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$
755767 }
756768
757769 // Equals
758770 //-----------------------------------------------------------------------
759771 /**
760 * <p>Compares two CharSequences, returning {@code true} if they are equal.</p>
772 * <p>Compares two CharSequences, returning {@code true} if they represent
773 * equal sequences of characters.</p>
761774 *
762775 * <p>{@code null}s are handled without exceptions. Two {@code null}
763776 * references are considered to be equal. The comparison is case sensitive.</p>
770783 * StringUtils.equals("abc", "ABC") = false
771784 * </pre>
772785 *
773 * @see java.lang.String#equals(Object)
774 * @param cs1 the first CharSequence, may be null
775 * @param cs2 the second CharSequence, may be null
776 * @return {@code true} if the CharSequences are equal, case sensitive, or
777 * both {@code null}
786 * @see Object#equals(Object)
787 * @param cs1 the first CharSequence, may be {@code null}
788 * @param cs2 the second CharSequence, may be {@code null}
789 * @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null}
778790 * @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
779791 */
780 public static boolean equals(CharSequence cs1, CharSequence cs2) {
781 return cs1 == null ? cs2 == null : cs1.equals(cs2);
782 }
783
784 /**
785 * <p>Compares two CharSequences, returning {@code true} if they are equal ignoring
786 * the case.</p>
792 public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
793 if (cs1 == cs2) {
794 return true;
795 }
796 if (cs1 == null || cs2 == null) {
797 return false;
798 }
799 if (cs1 instanceof String && cs2 instanceof String) {
800 return cs1.equals(cs2);
801 }
802 return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));
803 }
804
805 /**
806 * <p>Compares two CharSequences, returning {@code true} if they represent
807 * equal sequences of characters, ignoring case.</p>
787808 *
788809 * <p>{@code null}s are handled without exceptions. Two {@code null}
789810 * references are considered equal. Comparison is case insensitive.</p>
802823 * both {@code null}
803824 * @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence)
804825 */
805 public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2) {
826 public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) {
806827 if (str1 == null || str2 == null) {
807828 return str1 == str2;
829 } else if (str1 == str2) {
830 return true;
831 } else if (str1.length() != str2.length()) {
832 return false;
808833 } else {
809 return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, Math.max(str1.length(), str2.length()));
834 return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length());
810835 }
811836 }
812837
832857 * @since 2.0
833858 * @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int)
834859 */
835 public static int indexOf(CharSequence seq, int searchChar) {
860 public static int indexOf(final CharSequence seq, final int searchChar) {
836861 if (isEmpty(seq)) {
837862 return INDEX_NOT_FOUND;
838863 }
860885 * @param seq the CharSequence to check, may be null
861886 * @param searchChar the character to find
862887 * @param startPos the start position, negative treated as zero
863 * @return the first index of the search character,
888 * @return the first index of the search character (always &ge; startPos),
864889 * -1 if no match or {@code null} string input
865890 * @since 2.0
866891 * @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int)
867892 */
868 public static int indexOf(CharSequence seq, int searchChar, int startPos) {
893 public static int indexOf(final CharSequence seq, final int searchChar, final int startPos) {
869894 if (isEmpty(seq)) {
870895 return INDEX_NOT_FOUND;
871896 }
896921 * @since 2.0
897922 * @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence)
898923 */
899 public static int indexOf(CharSequence seq, CharSequence searchSeq) {
924 public static int indexOf(final CharSequence seq, final CharSequence searchSeq) {
900925 if (seq == null || searchSeq == null) {
901926 return INDEX_NOT_FOUND;
902927 }
931956 * @param seq the CharSequence to check, may be null
932957 * @param searchSeq the CharSequence to find, may be null
933958 * @param startPos the start position, negative treated as zero
934 * @return the first index of the search CharSequence,
959 * @return the first index of the search CharSequence (always &ge; startPos),
935960 * -1 if no match or {@code null} string input
936961 * @since 2.0
937962 * @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int)
938963 */
939 public static int indexOf(CharSequence seq, CharSequence searchSeq, int startPos) {
964 public static int indexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
940965 if (seq == null || searchSeq == null) {
941966 return INDEX_NOT_FOUND;
942967 }
9771002 * @since 2.1
9781003 * @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int)
9791004 */
980 public static int ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal) {
1005 public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
9811006 return ordinalIndexOf(str, searchStr, ordinal, false);
9821007 }
9831008
9951020 * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
9961021 */
9971022 // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)
998 private static int ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal, boolean lastIndex) {
1023 private static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal, final boolean lastIndex) {
9991024 if (str == null || searchStr == null || ordinal <= 0) {
10001025 return INDEX_NOT_FOUND;
10011026 }
10431068 * @since 2.5
10441069 * @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence)
10451070 */
1046 public static int indexOfIgnoreCase(CharSequence str, CharSequence searchStr) {
1071 public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
10471072 return indexOfIgnoreCase(str, searchStr, 0);
10481073 }
10491074
10741099 * @param str the CharSequence to check, may be null
10751100 * @param searchStr the CharSequence to find, may be null
10761101 * @param startPos the start position, negative treated as zero
1077 * @return the first index of the search CharSequence,
1102 * @return the first index of the search CharSequence (always &ge; startPos),
10781103 * -1 if no match or {@code null} string input
10791104 * @since 2.5
10801105 * @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int)
10811106 */
1082 public static int indexOfIgnoreCase(CharSequence str, CharSequence searchStr, int startPos) {
1107 public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
10831108 if (str == null || searchStr == null) {
10841109 return INDEX_NOT_FOUND;
10851110 }
10861111 if (startPos < 0) {
10871112 startPos = 0;
10881113 }
1089 int endLimit = str.length() - searchStr.length() + 1;
1114 final int endLimit = str.length() - searchStr.length() + 1;
10901115 if (startPos > endLimit) {
10911116 return INDEX_NOT_FOUND;
10921117 }
11231148 * @since 2.0
11241149 * @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int)
11251150 */
1126 public static int lastIndexOf(CharSequence seq, int searchChar) {
1151 public static int lastIndexOf(final CharSequence seq, final int searchChar) {
11271152 if (isEmpty(seq)) {
11281153 return INDEX_NOT_FOUND;
11291154 }
11371162 *
11381163 * <p>A {@code null} or empty ("") CharSequence will return {@code -1}.
11391164 * A negative start position returns {@code -1}.
1140 * A start position greater than the string length searches the whole string.</p>
1165 * A start position greater than the string length searches the whole string.
1166 * The search starts at the startPos and works backwards; matches starting after the start
1167 * position are ignored.
1168 * </p>
11411169 *
11421170 * <pre>
11431171 * StringUtils.lastIndexOf(null, *, *) = -1
11531181 * @param seq the CharSequence to check, may be null
11541182 * @param searchChar the character to find
11551183 * @param startPos the start position
1156 * @return the last index of the search character,
1184 * @return the last index of the search character (always &le; startPos),
11571185 * -1 if no match or {@code null} string input
11581186 * @since 2.0
11591187 * @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int)
11601188 */
1161 public static int lastIndexOf(CharSequence seq, int searchChar, int startPos) {
1189 public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) {
11621190 if (isEmpty(seq)) {
11631191 return INDEX_NOT_FOUND;
11641192 }
11881216 * @since 2.0
11891217 * @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence)
11901218 */
1191 public static int lastIndexOf(CharSequence seq, CharSequence searchSeq) {
1219 public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) {
11921220 if (seq == null || searchSeq == null) {
11931221 return INDEX_NOT_FOUND;
11941222 }
12291257 * @since 2.5
12301258 * @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int)
12311259 */
1232 public static int lastOrdinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal) {
1260 public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
12331261 return ordinalIndexOf(str, searchStr, ordinal, true);
12341262 }
12351263
12361264 /**
1237 * <p>Finds the first index within a CharSequence, handling {@code null}.
1265 * <p>Finds the last index within a CharSequence, handling {@code null}.
12381266 * This method uses {@link String#lastIndexOf(String, int)} if possible.</p>
12391267 *
12401268 * <p>A {@code null} CharSequence will return {@code -1}.
12411269 * A negative start position returns {@code -1}.
12421270 * An empty ("") search CharSequence always matches unless the start position is negative.
1243 * A start position greater than the string length searches the whole string.</p>
1271 * A start position greater than the string length searches the whole string.
1272 * The search starts at the startPos and works backwards; matches starting after the start
1273 * position are ignored.
1274 * </p>
12441275 *
12451276 * <pre>
12461277 * StringUtils.lastIndexOf(null, *, *) = -1
12521283 * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
12531284 * StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
12541285 * StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
1286 * StringUtils.lastIndexOf("aabaabaa", "b", 1) = -1
1287 * StringUtils.lastIndexOf("aabaabaa", "b", 2) = 2
1288 * StringUtils.lastIndexOf("aabaabaa", "ba", 2) = -1
1289 * StringUtils.lastIndexOf("aabaabaa", "ba", 2) = 2
12551290 * </pre>
12561291 *
12571292 * @param seq the CharSequence to check, may be null
12581293 * @param searchSeq the CharSequence to find, may be null
12591294 * @param startPos the start position, negative treated as zero
1260 * @return the first index of the search CharSequence,
1295 * @return the last index of the search CharSequence (always &le; startPos),
12611296 * -1 if no match or {@code null} string input
12621297 * @since 2.0
12631298 * @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int)
12641299 */
1265 public static int lastIndexOf(CharSequence seq, CharSequence searchSeq, int startPos) {
1300 public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
12661301 if (seq == null || searchSeq == null) {
12671302 return INDEX_NOT_FOUND;
12681303 }
12921327 * @since 2.5
12931328 * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence)
12941329 */
1295 public static int lastIndexOfIgnoreCase(CharSequence str, CharSequence searchStr) {
1330 public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
12961331 if (str == null || searchStr == null) {
12971332 return INDEX_NOT_FOUND;
12981333 }
13061341 * <p>A {@code null} CharSequence will return {@code -1}.
13071342 * A negative start position returns {@code -1}.
13081343 * An empty ("") search CharSequence always matches unless the start position is negative.
1309 * A start position greater than the string length searches the whole string.</p>
1344 * A start position greater than the string length searches the whole string.
1345 * The search starts at the startPos and works backwards; matches starting after the start
1346 * position are ignored.
1347 * </p>
13101348 *
13111349 * <pre>
13121350 * StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1
13231361 * @param str the CharSequence to check, may be null
13241362 * @param searchStr the CharSequence to find, may be null
13251363 * @param startPos the start position
1326 * @return the first index of the search CharSequence,
1364 * @return the last index of the search CharSequence (always &le; startPos),
13271365 * -1 if no match or {@code null} input
13281366 * @since 2.5
13291367 * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int)
13301368 */
1331 public static int lastIndexOfIgnoreCase(CharSequence str, CharSequence searchStr, int startPos) {
1369 public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
13321370 if (str == null || searchStr == null) {
13331371 return INDEX_NOT_FOUND;
13341372 }
13721410 * @since 2.0
13731411 * @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int)
13741412 */
1375 public static boolean contains(CharSequence seq, int searchChar) {
1413 public static boolean contains(final CharSequence seq, final int searchChar) {
13761414 if (isEmpty(seq)) {
13771415 return false;
13781416 }
14011439 * @since 2.0
14021440 * @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence)
14031441 */
1404 public static boolean contains(CharSequence seq, CharSequence searchSeq) {
1442 public static boolean contains(final CharSequence seq, final CharSequence searchSeq) {
14051443 if (seq == null || searchSeq == null) {
14061444 return false;
14071445 }
14321470 * case or false if not or {@code null} string input
14331471 * @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence)
14341472 */
1435 public static boolean containsIgnoreCase(CharSequence str, CharSequence searchStr) {
1473 public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) {
14361474 if (str == null || searchStr == null) {
14371475 return false;
14381476 }
1439 int len = searchStr.length();
1440 int max = str.length() - len;
1477 final int len = searchStr.length();
1478 final int max = str.length() - len;
14411479 for (int i = 0; i <= max; i++) {
14421480 if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) {
14431481 return true;
14551493 * @since 3.0
14561494 */
14571495 // From org.springframework.util.StringUtils, under Apache License 2.0
1458 public static boolean containsWhitespace(CharSequence seq) {
1496 public static boolean containsWhitespace(final CharSequence seq) {
14591497 if (isEmpty(seq)) {
14601498 return false;
14611499 }
1462 int strLen = seq.length();
1500 final int strLen = seq.length();
14631501 for (int i = 0; i < strLen; i++) {
14641502 if (Character.isWhitespace(seq.charAt(i))) {
14651503 return true;
14931531 * @since 2.0
14941532 * @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...)
14951533 */
1496 public static int indexOfAny(CharSequence cs, char... searchChars) {
1534 public static int indexOfAny(final CharSequence cs, final char... searchChars) {
14971535 if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
14981536 return INDEX_NOT_FOUND;
14991537 }
1500 int csLen = cs.length();
1501 int csLast = csLen - 1;
1502 int searchLen = searchChars.length;
1503 int searchLast = searchLen - 1;
1538 final int csLen = cs.length();
1539 final int csLast = csLen - 1;
1540 final int searchLen = searchChars.length;
1541 final int searchLast = searchLen - 1;
15041542 for (int i = 0; i < csLen; i++) {
1505 char ch = cs.charAt(i);
1543 final char ch = cs.charAt(i);
15061544 for (int j = 0; j < searchLen; j++) {
15071545 if (searchChars[j] == ch) {
15081546 if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
15421580 * @since 2.0
15431581 * @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String)
15441582 */
1545 public static int indexOfAny(CharSequence cs, String searchChars) {
1583 public static int indexOfAny(final CharSequence cs, final String searchChars) {
15461584 if (isEmpty(cs) || isEmpty(searchChars)) {
15471585 return INDEX_NOT_FOUND;
15481586 }
15751613 * @since 2.4
15761614 * @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...)
15771615 */
1578 public static boolean containsAny(CharSequence cs, char... searchChars) {
1616 public static boolean containsAny(final CharSequence cs, final char... searchChars) {
15791617 if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
15801618 return false;
15811619 }
1582 int csLength = cs.length();
1583 int searchLength = searchChars.length;
1584 int csLast = csLength - 1;
1585 int searchLast = searchLength - 1;
1620 final int csLength = cs.length();
1621 final int searchLength = searchChars.length;
1622 final int csLast = csLength - 1;
1623 final int searchLast = searchLength - 1;
15861624 for (int i = 0; i < csLength; i++) {
1587 char ch = cs.charAt(i);
1625 final char ch = cs.charAt(i);
15881626 for (int j = 0; j < searchLength; j++) {
15891627 if (searchChars[j] == ch) {
15901628 if (Character.isHighSurrogate(ch)) {
16331671 * @since 2.4
16341672 * @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence)
16351673 */
1636 public static boolean containsAny(CharSequence cs, CharSequence searchChars) {
1674 public static boolean containsAny(final CharSequence cs, final CharSequence searchChars) {
16371675 if (searchChars == null) {
16381676 return false;
16391677 }
16661704 * @since 2.0
16671705 * @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...)
16681706 */
1669 public static int indexOfAnyBut(CharSequence cs, char... searchChars) {
1707 public static int indexOfAnyBut(final CharSequence cs, final char... searchChars) {
16701708 if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
16711709 return INDEX_NOT_FOUND;
16721710 }
1673 int csLen = cs.length();
1674 int csLast = csLen - 1;
1675 int searchLen = searchChars.length;
1676 int searchLast = searchLen - 1;
1711 final int csLen = cs.length();
1712 final int csLast = csLen - 1;
1713 final int searchLen = searchChars.length;
1714 final int searchLast = searchLen - 1;
16771715 outer:
16781716 for (int i = 0; i < csLen; i++) {
1679 char ch = cs.charAt(i);
1717 final char ch = cs.charAt(i);
16801718 for (int j = 0; j < searchLen; j++) {
16811719 if (searchChars[j] == ch) {
16821720 if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
17161754 * @since 2.0
17171755 * @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence)
17181756 */
1719 public static int indexOfAnyBut(CharSequence seq, CharSequence searchChars) {
1757 public static int indexOfAnyBut(final CharSequence seq, final CharSequence searchChars) {
17201758 if (isEmpty(seq) || isEmpty(searchChars)) {
17211759 return INDEX_NOT_FOUND;
17221760 }
1723 int strLen = seq.length();
1761 final int strLen = seq.length();
17241762 for (int i = 0; i < strLen; i++) {
1725 char ch = seq.charAt(i);
1726 boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0;
1763 final char ch = seq.charAt(i);
1764 final boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0;
17271765 if (i + 1 < strLen && Character.isHighSurrogate(ch)) {
1728 char ch2 = seq.charAt(i + 1);
1766 final char ch2 = seq.charAt(i + 1);
17291767 if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) {
17301768 return i;
17311769 }
17621800 * @return true if it only contains valid chars and is non-null
17631801 * @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...)
17641802 */
1765 public static boolean containsOnly(CharSequence cs, char... valid) {
1803 public static boolean containsOnly(final CharSequence cs, final char... valid) {
17661804 // All these pre-checks are to maintain API with an older version
17671805 if (valid == null || cs == null) {
17681806 return false;
17991837 * @since 2.0
18001838 * @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String)
18011839 */
1802 public static boolean containsOnly(CharSequence cs, String validChars) {
1840 public static boolean containsOnly(final CharSequence cs, final String validChars) {
18031841 if (cs == null || validChars == null) {
18041842 return false;
18051843 }
18311869 * @since 2.0
18321870 * @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...)
18331871 */
1834 public static boolean containsNone(CharSequence cs, char... searchChars) {
1872 public static boolean containsNone(final CharSequence cs, final char... searchChars) {
18351873 if (cs == null || searchChars == null) {
18361874 return true;
18371875 }
1838 int csLen = cs.length();
1839 int csLast = csLen - 1;
1840 int searchLen = searchChars.length;
1841 int searchLast = searchLen - 1;
1876 final int csLen = cs.length();
1877 final int csLast = csLen - 1;
1878 final int searchLen = searchChars.length;
1879 final int searchLast = searchLen - 1;
18421880 for (int i = 0; i < csLen; i++) {
1843 char ch = cs.charAt(i);
1881 final char ch = cs.charAt(i);
18441882 for (int j = 0; j < searchLen; j++) {
18451883 if (searchChars[j] == ch) {
18461884 if (Character.isHighSurrogate(ch)) {
18841922 * @since 2.0
18851923 * @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String)
18861924 */
1887 public static boolean containsNone(CharSequence cs, String invalidChars) {
1925 public static boolean containsNone(final CharSequence cs, final String invalidChars) {
18881926 if (cs == null || invalidChars == null) {
18891927 return true;
18901928 }
19201958 * @return the first index of any of the searchStrs in str, -1 if no match
19211959 * @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...)
19221960 */
1923 public static int indexOfAny(CharSequence str, CharSequence... searchStrs) {
1961 public static int indexOfAny(final CharSequence str, final CharSequence... searchStrs) {
19241962 if (str == null || searchStrs == null) {
19251963 return INDEX_NOT_FOUND;
19261964 }
1927 int sz = searchStrs.length;
1965 final int sz = searchStrs.length;
19281966
19291967 // String's can't have a MAX_VALUEth index.
19301968 int ret = Integer.MAX_VALUE;
19311969
19321970 int tmp = 0;
19331971 for (int i = 0; i < sz; i++) {
1934 CharSequence search = searchStrs[i];
1972 final CharSequence search = searchStrs[i];
19351973 if (search == null) {
19361974 continue;
19371975 }
19742012 * @return the last index of any of the CharSequences, -1 if no match
19752013 * @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence)
19762014 */
1977 public static int lastIndexOfAny(CharSequence str, CharSequence... searchStrs) {
2015 public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) {
19782016 if (str == null || searchStrs == null) {
19792017 return INDEX_NOT_FOUND;
19802018 }
1981 int sz = searchStrs.length;
2019 final int sz = searchStrs.length;
19822020 int ret = INDEX_NOT_FOUND;
19832021 int tmp = 0;
19842022 for (int i = 0; i < sz; i++) {
1985 CharSequence search = searchStrs[i];
2023 final CharSequence search = searchStrs[i];
19862024 if (search == null) {
19872025 continue;
19882026 }
20202058 * count back from the end of the String by this many characters
20212059 * @return substring from start position, {@code null} if null String input
20222060 */
2023 public static String substring(String str, int start) {
2061 public static String substring(final String str, int start) {
20242062 if (str == null) {
20252063 return null;
20262064 }
20752113 * @return substring from start position to end position,
20762114 * {@code null} if null String input
20772115 */
2078 public static String substring(String str, int start, int end) {
2116 public static String substring(final String str, int start, int end) {
20792117 if (str == null) {
20802118 return null;
20812119 }
21302168 * @param len the length of the required String
21312169 * @return the leftmost characters, {@code null} if null String input
21322170 */
2133 public static String left(String str, int len) {
2171 public static String left(final String str, final int len) {
21342172 if (str == null) {
21352173 return null;
21362174 }
21632201 * @param len the length of the required String
21642202 * @return the rightmost characters, {@code null} if null String input
21652203 */
2166 public static String right(String str, int len) {
2204 public static String right(final String str, final int len) {
21672205 if (str == null) {
21682206 return null;
21692207 }
22012239 * @param len the length of the required String
22022240 * @return the middle characters, {@code null} if null String input
22032241 */
2204 public static String mid(String str, int pos, int len) {
2242 public static String mid(final String str, int pos, final int len) {
22052243 if (str == null) {
22062244 return null;
22072245 }
22462284 * {@code null} if null String input
22472285 * @since 2.0
22482286 */
2249 public static String substringBefore(String str, String separator) {
2287 public static String substringBefore(final String str, final String separator) {
22502288 if (isEmpty(str) || separator == null) {
22512289 return str;
22522290 }
2253 if (separator.length() == 0) {
2291 if (separator.isEmpty()) {
22542292 return EMPTY;
22552293 }
2256 int pos = str.indexOf(separator);
2294 final int pos = str.indexOf(separator);
22572295 if (pos == INDEX_NOT_FOUND) {
22582296 return str;
22592297 }
22882326 * {@code null} if null String input
22892327 * @since 2.0
22902328 */
2291 public static String substringAfter(String str, String separator) {
2329 public static String substringAfter(final String str, final String separator) {
22922330 if (isEmpty(str)) {
22932331 return str;
22942332 }
22952333 if (separator == null) {
22962334 return EMPTY;
22972335 }
2298 int pos = str.indexOf(separator);
2336 final int pos = str.indexOf(separator);
22992337 if (pos == INDEX_NOT_FOUND) {
23002338 return EMPTY;
23012339 }
23292367 * {@code null} if null String input
23302368 * @since 2.0
23312369 */
2332 public static String substringBeforeLast(String str, String separator) {
2370 public static String substringBeforeLast(final String str, final String separator) {
23332371 if (isEmpty(str) || isEmpty(separator)) {
23342372 return str;
23352373 }
2336 int pos = str.lastIndexOf(separator);
2374 final int pos = str.lastIndexOf(separator);
23372375 if (pos == INDEX_NOT_FOUND) {
23382376 return str;
23392377 }
23692407 * {@code null} if null String input
23702408 * @since 2.0
23712409 */
2372 public static String substringAfterLast(String str, String separator) {
2410 public static String substringAfterLast(final String str, final String separator) {
23732411 if (isEmpty(str)) {
23742412 return str;
23752413 }
23762414 if (isEmpty(separator)) {
23772415 return EMPTY;
23782416 }
2379 int pos = str.lastIndexOf(separator);
2417 final int pos = str.lastIndexOf(separator);
23802418 if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) {
23812419 return EMPTY;
23822420 }
24062444 * @return the substring, {@code null} if no match
24072445 * @since 2.0
24082446 */
2409 public static String substringBetween(String str, String tag) {
2447 public static String substringBetween(final String str, final String tag) {
24102448 return substringBetween(str, tag, tag);
24112449 }
24122450
24372475 * @return the substring, {@code null} if no match
24382476 * @since 2.0
24392477 */
2440 public static String substringBetween(String str, String open, String close) {
2478 public static String substringBetween(final String str, final String open, final String close) {
24412479 if (str == null || open == null || close == null) {
24422480 return null;
24432481 }
2444 int start = str.indexOf(open);
2482 final int start = str.indexOf(open);
24452483 if (start != INDEX_NOT_FOUND) {
2446 int end = str.indexOf(close, start + open.length());
2484 final int end = str.indexOf(close, start + open.length());
24472485 if (end != INDEX_NOT_FOUND) {
24482486 return str.substring(start + open.length(), end);
24492487 }
24732511 * @return a String Array of substrings, or {@code null} if no match
24742512 * @since 2.3
24752513 */
2476 public static String[] substringsBetween(String str, String open, String close) {
2514 public static String[] substringsBetween(final String str, final String open, final String close) {
24772515 if (str == null || isEmpty(open) || isEmpty(close)) {
24782516 return null;
24792517 }
2480 int strLen = str.length();
2518 final int strLen = str.length();
24812519 if (strLen == 0) {
24822520 return ArrayUtils.EMPTY_STRING_ARRAY;
24832521 }
2484 int closeLen = close.length();
2485 int openLen = open.length();
2486 List<String> list = new ArrayList<String>();
2522 final int closeLen = close.length();
2523 final int openLen = open.length();
2524 final List<String> list = new ArrayList<String>();
24872525 int pos = 0;
24882526 while (pos < strLen - closeLen) {
24892527 int start = str.indexOf(open, pos);
24912529 break;
24922530 }
24932531 start += openLen;
2494 int end = str.indexOf(close, start);
2532 final int end = str.indexOf(close, start);
24952533 if (end < 0) {
24962534 break;
24972535 }
25312569 * @param str the String to parse, may be null
25322570 * @return an array of parsed Strings, {@code null} if null String input
25332571 */
2534 public static String[] split(String str) {
2572 public static String[] split(final String str) {
25352573 return split(str, null, -1);
25362574 }
25372575
25592597 * @return an array of parsed Strings, {@code null} if null String input
25602598 * @since 2.0
25612599 */
2562 public static String[] split(String str, char separatorChar) {
2600 public static String[] split(final String str, final char separatorChar) {
25632601 return splitWorker(str, separatorChar, false);
25642602 }
25652603
25882626 * {@code null} splits on whitespace
25892627 * @return an array of parsed Strings, {@code null} if null String input
25902628 */
2591 public static String[] split(String str, String separatorChars) {
2629 public static String[] split(final String str, final String separatorChars) {
25922630 return splitWorker(str, separatorChars, -1, false);
25932631 }
25942632
26092647 * <pre>
26102648 * StringUtils.split(null, *, *) = null
26112649 * StringUtils.split("", *, *) = []
2612 * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
2613 * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
2650 * StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
2651 * StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
26142652 * StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
26152653 * StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
26162654 * </pre>
26222660 * array. A zero or negative value implies no limit
26232661 * @return an array of parsed Strings, {@code null} if null String input
26242662 */
2625 public static String[] split(String str, String separatorChars, int max) {
2663 public static String[] split(final String str, final String separatorChars, final int max) {
26262664 return splitWorker(str, separatorChars, max, false);
26272665 }
26282666
26492687 * {@code null} splits on whitespace
26502688 * @return an array of parsed Strings, {@code null} if null String was input
26512689 */
2652 public static String[] splitByWholeSeparator(String str, String separator) {
2690 public static String[] splitByWholeSeparator(final String str, final String separator) {
26532691 return splitByWholeSeparatorWorker( str, separator, -1, false ) ;
26542692 }
26552693
26802718 * array. A zero or negative value implies no limit.
26812719 * @return an array of parsed Strings, {@code null} if null String was input
26822720 */
2683 public static String[] splitByWholeSeparator( String str, String separator, int max ) {
2721 public static String[] splitByWholeSeparator( final String str, final String separator, final int max ) {
26842722 return splitByWholeSeparatorWorker(str, separator, max, false);
26852723 }
26862724
27092747 * @return an array of parsed Strings, {@code null} if null String was input
27102748 * @since 2.4
27112749 */
2712 public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator) {
2750 public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {
27132751 return splitByWholeSeparatorWorker(str, separator, -1, true);
27142752 }
27152753
27422780 * @return an array of parsed Strings, {@code null} if null String was input
27432781 * @since 2.4
27442782 */
2745 public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator, int max) {
2783 public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {
27462784 return splitByWholeSeparatorWorker(str, separator, max, true);
27472785 }
27482786
27612799 * @since 2.4
27622800 */
27632801 private static String[] splitByWholeSeparatorWorker(
2764 String str, String separator, int max, boolean preserveAllTokens) {
2802 final String str, final String separator, final int max, final boolean preserveAllTokens) {
27652803 if (str == null) {
27662804 return null;
27672805 }
27682806
2769 int len = str.length();
2807 final int len = str.length();
27702808
27712809 if (len == 0) {
27722810 return ArrayUtils.EMPTY_STRING_ARRAY;
27772815 return splitWorker(str, null, max, preserveAllTokens);
27782816 }
27792817
2780 int separatorLength = separator.length();
2781
2782 ArrayList<String> substrings = new ArrayList<String>();
2818 final int separatorLength = separator.length();
2819
2820 final ArrayList<String> substrings = new ArrayList<String>();
27832821 int numberOfSubstrings = 0;
27842822 int beg = 0;
27852823 int end = 0;
28512889 * @return an array of parsed Strings, {@code null} if null String input
28522890 * @since 2.1
28532891 */
2854 public static String[] splitPreserveAllTokens(String str) {
2892 public static String[] splitPreserveAllTokens(final String str) {
28552893 return splitWorker(str, null, -1, true);
28562894 }
28572895
28872925 * @return an array of parsed Strings, {@code null} if null String input
28882926 * @since 2.1
28892927 */
2890 public static String[] splitPreserveAllTokens(String str, char separatorChar) {
2928 public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {
28912929 return splitWorker(str, separatorChar, true);
28922930 }
28932931
29032941 * separators are treated as one separator.
29042942 * @return an array of parsed Strings, {@code null} if null String input
29052943 */
2906 private static String[] splitWorker(String str, char separatorChar, boolean preserveAllTokens) {
2944 private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {
29072945 // Performance tuned for 2.0 (JDK1.4)
29082946
29092947 if (str == null) {
29102948 return null;
29112949 }
2912 int len = str.length();
2950 final int len = str.length();
29132951 if (len == 0) {
29142952 return ArrayUtils.EMPTY_STRING_ARRAY;
29152953 }
2916 List<String> list = new ArrayList<String>();
2954 final List<String> list = new ArrayList<String>();
29172955 int i = 0, start = 0;
29182956 boolean match = false;
29192957 boolean lastMatch = false;
29703008 * @return an array of parsed Strings, {@code null} if null String input
29713009 * @since 2.1
29723010 */
2973 public static String[] splitPreserveAllTokens(String str, String separatorChars) {
3011 public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {
29743012 return splitWorker(str, separatorChars, -1, true);
29753013 }
29763014
30103048 * @return an array of parsed Strings, {@code null} if null String input
30113049 * @since 2.1
30123050 */
3013 public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) {
3051 public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {
30143052 return splitWorker(str, separatorChars, max, true);
30153053 }
30163054
30283066 * separators are treated as one separator.
30293067 * @return an array of parsed Strings, {@code null} if null String input
30303068 */
3031 private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) {
3069 private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {
30323070 // Performance tuned for 2.0 (JDK1.4)
30333071 // Direct code is quicker than StringTokenizer.
30343072 // Also, StringTokenizer uses isSpace() not isWhitespace()
30363074 if (str == null) {
30373075 return null;
30383076 }
3039 int len = str.length();
3077 final int len = str.length();
30403078 if (len == 0) {
30413079 return ArrayUtils.EMPTY_STRING_ARRAY;
30423080 }
3043 List<String> list = new ArrayList<String>();
3081 final List<String> list = new ArrayList<String>();
30443082 int sizePlus1 = 1;
30453083 int i = 0, start = 0;
30463084 boolean match = false;
30673105 }
30683106 } else if (separatorChars.length() == 1) {
30693107 // Optimise 1 character case
3070 char sep = separatorChars.charAt(0);
3108 final char sep = separatorChars.charAt(0);
30713109 while (i < len) {
30723110 if (str.charAt(i) == sep) {
30733111 if (match || preserveAllTokens) {
31323170 * @return an array of parsed Strings, {@code null} if null String input
31333171 * @since 2.4
31343172 */
3135 public static String[] splitByCharacterType(String str) {
3173 public static String[] splitByCharacterType(final String str) {
31363174 return splitByCharacterType(str, false);
31373175 }
31383176
31603198 * @return an array of parsed Strings, {@code null} if null String input
31613199 * @since 2.4
31623200 */
3163 public static String[] splitByCharacterTypeCamelCase(String str) {
3201 public static String[] splitByCharacterTypeCamelCase(final String str) {
31643202 return splitByCharacterType(str, true);
31653203 }
31663204
31783216 * @return an array of parsed Strings, {@code null} if null String input
31793217 * @since 2.4
31803218 */
3181 private static String[] splitByCharacterType(String str, boolean camelCase) {
3219 private static String[] splitByCharacterType(final String str, final boolean camelCase) {
31823220 if (str == null) {
31833221 return null;
31843222 }
3185 if (str.length() == 0) {
3223 if (str.isEmpty()) {
31863224 return ArrayUtils.EMPTY_STRING_ARRAY;
31873225 }
3188 char[] c = str.toCharArray();
3189 List<String> list = new ArrayList<String>();
3226 final char[] c = str.toCharArray();
3227 final List<String> list = new ArrayList<String>();
31903228 int tokenStart = 0;
31913229 int currentType = Character.getType(c[tokenStart]);
31923230 for (int pos = tokenStart + 1; pos < c.length; pos++) {
3193 int type = Character.getType(c[pos]);
3231 final int type = Character.getType(c[pos]);
31943232 if (type == currentType) {
31953233 continue;
31963234 }
31973235 if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {
3198 int newTokenStart = pos - 1;
3236 final int newTokenStart = pos - 1;
31993237 if (newTokenStart != tokenStart) {
32003238 list.add(new String(c, tokenStart, newTokenStart - tokenStart));
32013239 tokenStart = newTokenStart;
32343272 * @since 2.0
32353273 * @since 3.0 Changed signature to use varargs
32363274 */
3237 public static <T> String join(T... elements) {
3275 public static <T> String join(final T... elements) {
32383276 return join(elements, null);
32393277 }
32403278
32603298 * @return the joined String, {@code null} if null array input
32613299 * @since 2.0
32623300 */
3263 public static String join(Object[] array, char separator) {
3301 public static String join(final Object[] array, final char separator) {
32643302 if (array == null) {
32653303 return null;
32663304 }
3267
32683305 return join(array, separator, 0, array.length);
32693306 }
3307
3308 /**
3309 * <p>
3310 * Joins the elements of the provided array into a single String containing the provided list of elements.
3311 * </p>
3312 *
3313 * <p>
3314 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3315 * by empty strings.
3316 * </p>
3317 *
3318 * <pre>
3319 * StringUtils.join(null, *) = null
3320 * StringUtils.join([], *) = ""
3321 * StringUtils.join([null], *) = ""
3322 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3323 * StringUtils.join([1, 2, 3], null) = "123"
3324 * </pre>
3325 *
3326 * @param array
3327 * the array of values to join together, may be null
3328 * @param separator
3329 * the separator character to use
3330 * @return the joined String, {@code null} if null array input
3331 * @since 3.2
3332 */
3333 public static String join(final long[] array, final char separator) {
3334 if (array == null) {
3335 return null;
3336 }
3337 return join(array, separator, 0, array.length);
3338 }
3339
3340 /**
3341 * <p>
3342 * Joins the elements of the provided array into a single String containing the provided list of elements.
3343 * </p>
3344 *
3345 * <p>
3346 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3347 * by empty strings.
3348 * </p>
3349 *
3350 * <pre>
3351 * StringUtils.join(null, *) = null
3352 * StringUtils.join([], *) = ""
3353 * StringUtils.join([null], *) = ""
3354 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3355 * StringUtils.join([1, 2, 3], null) = "123"
3356 * </pre>
3357 *
3358 * @param array
3359 * the array of values to join together, may be null
3360 * @param separator
3361 * the separator character to use
3362 * @return the joined String, {@code null} if null array input
3363 * @since 3.2
3364 */
3365 public static String join(final int[] array, final char separator) {
3366 if (array == null) {
3367 return null;
3368 }
3369 return join(array, separator, 0, array.length);
3370 }
3371
3372 /**
3373 * <p>
3374 * Joins the elements of the provided array into a single String containing the provided list of elements.
3375 * </p>
3376 *
3377 * <p>
3378 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3379 * by empty strings.
3380 * </p>
3381 *
3382 * <pre>
3383 * StringUtils.join(null, *) = null
3384 * StringUtils.join([], *) = ""
3385 * StringUtils.join([null], *) = ""
3386 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3387 * StringUtils.join([1, 2, 3], null) = "123"
3388 * </pre>
3389 *
3390 * @param array
3391 * the array of values to join together, may be null
3392 * @param separator
3393 * the separator character to use
3394 * @return the joined String, {@code null} if null array input
3395 * @since 3.2
3396 */
3397 public static String join(final short[] array, final char separator) {
3398 if (array == null) {
3399 return null;
3400 }
3401 return join(array, separator, 0, array.length);
3402 }
3403
3404 /**
3405 * <p>
3406 * Joins the elements of the provided array into a single String containing the provided list of elements.
3407 * </p>
3408 *
3409 * <p>
3410 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3411 * by empty strings.
3412 * </p>
3413 *
3414 * <pre>
3415 * StringUtils.join(null, *) = null
3416 * StringUtils.join([], *) = ""
3417 * StringUtils.join([null], *) = ""
3418 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3419 * StringUtils.join([1, 2, 3], null) = "123"
3420 * </pre>
3421 *
3422 * @param array
3423 * the array of values to join together, may be null
3424 * @param separator
3425 * the separator character to use
3426 * @return the joined String, {@code null} if null array input
3427 * @since 3.2
3428 */
3429 public static String join(final byte[] array, final char separator) {
3430 if (array == null) {
3431 return null;
3432 }
3433 return join(array, separator, 0, array.length);
3434 }
3435
3436 /**
3437 * <p>
3438 * Joins the elements of the provided array into a single String containing the provided list of elements.
3439 * </p>
3440 *
3441 * <p>
3442 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3443 * by empty strings.
3444 * </p>
3445 *
3446 * <pre>
3447 * StringUtils.join(null, *) = null
3448 * StringUtils.join([], *) = ""
3449 * StringUtils.join([null], *) = ""
3450 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3451 * StringUtils.join([1, 2, 3], null) = "123"
3452 * </pre>
3453 *
3454 * @param array
3455 * the array of values to join together, may be null
3456 * @param separator
3457 * the separator character to use
3458 * @return the joined String, {@code null} if null array input
3459 * @since 3.2
3460 */
3461 public static String join(final char[] array, final char separator) {
3462 if (array == null) {
3463 return null;
3464 }
3465 return join(array, separator, 0, array.length);
3466 }
3467
3468 /**
3469 * <p>
3470 * Joins the elements of the provided array into a single String containing the provided list of elements.
3471 * </p>
3472 *
3473 * <p>
3474 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3475 * by empty strings.
3476 * </p>
3477 *
3478 * <pre>
3479 * StringUtils.join(null, *) = null
3480 * StringUtils.join([], *) = ""
3481 * StringUtils.join([null], *) = ""
3482 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3483 * StringUtils.join([1, 2, 3], null) = "123"
3484 * </pre>
3485 *
3486 * @param array
3487 * the array of values to join together, may be null
3488 * @param separator
3489 * the separator character to use
3490 * @return the joined String, {@code null} if null array input
3491 * @since 3.2
3492 */
3493 public static String join(final float[] array, final char separator) {
3494 if (array == null) {
3495 return null;
3496 }
3497 return join(array, separator, 0, array.length);
3498 }
3499
3500 /**
3501 * <p>
3502 * Joins the elements of the provided array into a single String containing the provided list of elements.
3503 * </p>
3504 *
3505 * <p>
3506 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3507 * by empty strings.
3508 * </p>
3509 *
3510 * <pre>
3511 * StringUtils.join(null, *) = null
3512 * StringUtils.join([], *) = ""
3513 * StringUtils.join([null], *) = ""
3514 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3515 * StringUtils.join([1, 2, 3], null) = "123"
3516 * </pre>
3517 *
3518 * @param array
3519 * the array of values to join together, may be null
3520 * @param separator
3521 * the separator character to use
3522 * @return the joined String, {@code null} if null array input
3523 * @since 3.2
3524 */
3525 public static String join(final double[] array, final char separator) {
3526 if (array == null) {
3527 return null;
3528 }
3529 return join(array, separator, 0, array.length);
3530 }
3531
32703532
32713533 /**
32723534 * <p>Joins the elements of the provided array into a single String
32943556 * @return the joined String, {@code null} if null array input
32953557 * @since 2.0
32963558 */
3297 public static String join(Object[] array, char separator, int startIndex, int endIndex) {
3559 public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {
32983560 if (array == null) {
32993561 return null;
33003562 }
3301 int noOfItems = endIndex - startIndex;
3563 final int noOfItems = endIndex - startIndex;
33023564 if (noOfItems <= 0) {
33033565 return EMPTY;
33043566 }
3305
3306 StringBuilder buf = new StringBuilder(noOfItems * 16);
3307
3567 final StringBuilder buf = new StringBuilder(noOfItems * 16);
33083568 for (int i = startIndex; i < endIndex; i++) {
33093569 if (i > startIndex) {
33103570 buf.append(separator);
33153575 }
33163576 return buf.toString();
33173577 }
3578
3579 /**
3580 * <p>
3581 * Joins the elements of the provided array into a single String containing the provided list of elements.
3582 * </p>
3583 *
3584 * <p>
3585 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3586 * by empty strings.
3587 * </p>
3588 *
3589 * <pre>
3590 * StringUtils.join(null, *) = null
3591 * StringUtils.join([], *) = ""
3592 * StringUtils.join([null], *) = ""
3593 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3594 * StringUtils.join([1, 2, 3], null) = "123"
3595 * </pre>
3596 *
3597 * @param array
3598 * the array of values to join together, may be null
3599 * @param separator
3600 * the separator character to use
3601 * @param startIndex
3602 * the first index to start joining from. It is an error to pass in an end index past the end of the
3603 * array
3604 * @param endIndex
3605 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3606 * the array
3607 * @return the joined String, {@code null} if null array input
3608 * @since 3.2
3609 */
3610 public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) {
3611 if (array == null) {
3612 return null;
3613 }
3614 final int noOfItems = endIndex - startIndex;
3615 if (noOfItems <= 0) {
3616 return EMPTY;
3617 }
3618 final StringBuilder buf = new StringBuilder(noOfItems * 16);
3619 for (int i = startIndex; i < endIndex; i++) {
3620 if (i > startIndex) {
3621 buf.append(separator);
3622 }
3623 buf.append(array[i]);
3624 }
3625 return buf.toString();
3626 }
3627
3628 /**
3629 * <p>
3630 * Joins the elements of the provided array into a single String containing the provided list of elements.
3631 * </p>
3632 *
3633 * <p>
3634 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3635 * by empty strings.
3636 * </p>
3637 *
3638 * <pre>
3639 * StringUtils.join(null, *) = null
3640 * StringUtils.join([], *) = ""
3641 * StringUtils.join([null], *) = ""
3642 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3643 * StringUtils.join([1, 2, 3], null) = "123"
3644 * </pre>
3645 *
3646 * @param array
3647 * the array of values to join together, may be null
3648 * @param separator
3649 * the separator character to use
3650 * @param startIndex
3651 * the first index to start joining from. It is an error to pass in an end index past the end of the
3652 * array
3653 * @param endIndex
3654 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3655 * the array
3656 * @return the joined String, {@code null} if null array input
3657 * @since 3.2
3658 */
3659 public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) {
3660 if (array == null) {
3661 return null;
3662 }
3663 final int noOfItems = endIndex - startIndex;
3664 if (noOfItems <= 0) {
3665 return EMPTY;
3666 }
3667 final StringBuilder buf = new StringBuilder(noOfItems * 16);
3668 for (int i = startIndex; i < endIndex; i++) {
3669 if (i > startIndex) {
3670 buf.append(separator);
3671 }
3672 buf.append(array[i]);
3673 }
3674 return buf.toString();
3675 }
3676
3677 /**
3678 * <p>
3679 * Joins the elements of the provided array into a single String containing the provided list of elements.
3680 * </p>
3681 *
3682 * <p>
3683 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3684 * by empty strings.
3685 * </p>
3686 *
3687 * <pre>
3688 * StringUtils.join(null, *) = null
3689 * StringUtils.join([], *) = ""
3690 * StringUtils.join([null], *) = ""
3691 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3692 * StringUtils.join([1, 2, 3], null) = "123"
3693 * </pre>
3694 *
3695 * @param array
3696 * the array of values to join together, may be null
3697 * @param separator
3698 * the separator character to use
3699 * @param startIndex
3700 * the first index to start joining from. It is an error to pass in an end index past the end of the
3701 * array
3702 * @param endIndex
3703 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3704 * the array
3705 * @return the joined String, {@code null} if null array input
3706 * @since 3.2
3707 */
3708 public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) {
3709 if (array == null) {
3710 return null;
3711 }
3712 final int noOfItems = endIndex - startIndex;
3713 if (noOfItems <= 0) {
3714 return EMPTY;
3715 }
3716 final StringBuilder buf = new StringBuilder(noOfItems * 16);
3717 for (int i = startIndex; i < endIndex; i++) {
3718 if (i > startIndex) {
3719 buf.append(separator);
3720 }
3721 buf.append(array[i]);
3722 }
3723 return buf.toString();
3724 }
3725
3726 /**
3727 * <p>
3728 * Joins the elements of the provided array into a single String containing the provided list of elements.
3729 * </p>
3730 *
3731 * <p>
3732 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3733 * by empty strings.
3734 * </p>
3735 *
3736 * <pre>
3737 * StringUtils.join(null, *) = null
3738 * StringUtils.join([], *) = ""
3739 * StringUtils.join([null], *) = ""
3740 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3741 * StringUtils.join([1, 2, 3], null) = "123"
3742 * </pre>
3743 *
3744 * @param array
3745 * the array of values to join together, may be null
3746 * @param separator
3747 * the separator character to use
3748 * @param startIndex
3749 * the first index to start joining from. It is an error to pass in an end index past the end of the
3750 * array
3751 * @param endIndex
3752 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3753 * the array
3754 * @return the joined String, {@code null} if null array input
3755 * @since 3.2
3756 */
3757 public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) {
3758 if (array == null) {
3759 return null;
3760 }
3761 final int noOfItems = endIndex - startIndex;
3762 if (noOfItems <= 0) {
3763 return EMPTY;
3764 }
3765 final StringBuilder buf = new StringBuilder(noOfItems * 16);
3766 for (int i = startIndex; i < endIndex; i++) {
3767 if (i > startIndex) {
3768 buf.append(separator);
3769 }
3770 buf.append(array[i]);
3771 }
3772 return buf.toString();
3773 }
3774
3775 /**
3776 * <p>
3777 * Joins the elements of the provided array into a single String containing the provided list of elements.
3778 * </p>
3779 *
3780 * <p>
3781 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3782 * by empty strings.
3783 * </p>
3784 *
3785 * <pre>
3786 * StringUtils.join(null, *) = null
3787 * StringUtils.join([], *) = ""
3788 * StringUtils.join([null], *) = ""
3789 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3790 * StringUtils.join([1, 2, 3], null) = "123"
3791 * </pre>
3792 *
3793 * @param array
3794 * the array of values to join together, may be null
3795 * @param separator
3796 * the separator character to use
3797 * @param startIndex
3798 * the first index to start joining from. It is an error to pass in an end index past the end of the
3799 * array
3800 * @param endIndex
3801 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3802 * the array
3803 * @return the joined String, {@code null} if null array input
3804 * @since 3.2
3805 */
3806 public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) {
3807 if (array == null) {
3808 return null;
3809 }
3810 final int noOfItems = endIndex - startIndex;
3811 if (noOfItems <= 0) {
3812 return EMPTY;
3813 }
3814 final StringBuilder buf = new StringBuilder(noOfItems * 16);
3815 for (int i = startIndex; i < endIndex; i++) {
3816 if (i > startIndex) {
3817 buf.append(separator);
3818 }
3819 buf.append(array[i]);
3820 }
3821 return buf.toString();
3822 }
3823
3824 /**
3825 * <p>
3826 * Joins the elements of the provided array into a single String containing the provided list of elements.
3827 * </p>
3828 *
3829 * <p>
3830 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3831 * by empty strings.
3832 * </p>
3833 *
3834 * <pre>
3835 * StringUtils.join(null, *) = null
3836 * StringUtils.join([], *) = ""
3837 * StringUtils.join([null], *) = ""
3838 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3839 * StringUtils.join([1, 2, 3], null) = "123"
3840 * </pre>
3841 *
3842 * @param array
3843 * the array of values to join together, may be null
3844 * @param separator
3845 * the separator character to use
3846 * @param startIndex
3847 * the first index to start joining from. It is an error to pass in an end index past the end of the
3848 * array
3849 * @param endIndex
3850 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3851 * the array
3852 * @return the joined String, {@code null} if null array input
3853 * @since 3.2
3854 */
3855 public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) {
3856 if (array == null) {
3857 return null;
3858 }
3859 final int noOfItems = endIndex - startIndex;
3860 if (noOfItems <= 0) {
3861 return EMPTY;
3862 }
3863 final StringBuilder buf = new StringBuilder(noOfItems * 16);
3864 for (int i = startIndex; i < endIndex; i++) {
3865 if (i > startIndex) {
3866 buf.append(separator);
3867 }
3868 buf.append(array[i]);
3869 }
3870 return buf.toString();
3871 }
3872
3873 /**
3874 * <p>
3875 * Joins the elements of the provided array into a single String containing the provided list of elements.
3876 * </p>
3877 *
3878 * <p>
3879 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3880 * by empty strings.
3881 * </p>
3882 *
3883 * <pre>
3884 * StringUtils.join(null, *) = null
3885 * StringUtils.join([], *) = ""
3886 * StringUtils.join([null], *) = ""
3887 * StringUtils.join([1, 2, 3], ';') = "1;2;3"
3888 * StringUtils.join([1, 2, 3], null) = "123"
3889 * </pre>
3890 *
3891 * @param array
3892 * the array of values to join together, may be null
3893 * @param separator
3894 * the separator character to use
3895 * @param startIndex
3896 * the first index to start joining from. It is an error to pass in an end index past the end of the
3897 * array
3898 * @param endIndex
3899 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3900 * the array
3901 * @return the joined String, {@code null} if null array input
3902 * @since 3.2
3903 */
3904 public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) {
3905 if (array == null) {
3906 return null;
3907 }
3908 final int noOfItems = endIndex - startIndex;
3909 if (noOfItems <= 0) {
3910 return EMPTY;
3911 }
3912 final StringBuilder buf = new StringBuilder(noOfItems * 16);
3913 for (int i = startIndex; i < endIndex; i++) {
3914 if (i > startIndex) {
3915 buf.append(separator);
3916 }
3917 buf.append(array[i]);
3918 }
3919 return buf.toString();
3920 }
3921
33183922
33193923 /**
33203924 * <p>Joins the elements of the provided array into a single String
33393943 * @param separator the separator character to use, null treated as ""
33403944 * @return the joined String, {@code null} if null array input
33413945 */
3342 public static String join(Object[] array, String separator) {
3946 public static String join(final Object[] array, final String separator) {
33433947 if (array == null) {
33443948 return null;
33453949 }
33563960 * empty strings.</p>
33573961 *
33583962 * <pre>
3359 * StringUtils.join(null, *) = null
3360 * StringUtils.join([], *) = ""
3361 * StringUtils.join([null], *) = ""
3362 * StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
3363 * StringUtils.join(["a", "b", "c"], null) = "abc"
3364 * StringUtils.join(["a", "b", "c"], "") = "abc"
3365 * StringUtils.join([null, "", "a"], ',') = ",,a"
3963 * StringUtils.join(null, *, *, *) = null
3964 * StringUtils.join([], *, *, *) = ""
3965 * StringUtils.join([null], *, *, *) = ""
3966 * StringUtils.join(["a", "b", "c"], "--", 0, 3) = "a--b--c"
3967 * StringUtils.join(["a", "b", "c"], "--", 1, 3) = "b--c"
3968 * StringUtils.join(["a", "b", "c"], "--", 2, 3) = "c"
3969 * StringUtils.join(["a", "b", "c"], "--", 2, 2) = ""
3970 * StringUtils.join(["a", "b", "c"], null, 0, 3) = "abc"
3971 * StringUtils.join(["a", "b", "c"], "", 0, 3) = "abc"
3972 * StringUtils.join([null, "", "a"], ',', 0, 3) = ",,a"
33663973 * </pre>
33673974 *
33683975 * @param array the array of values to join together, may be null
33693976 * @param separator the separator character to use, null treated as ""
3370 * @param startIndex the first index to start joining from. It is
3371 * an error to pass in an end index past the end of the array
3372 * @param endIndex the index to stop joining from (exclusive). It is
3373 * an error to pass in an end index past the end of the array
3374 * @return the joined String, {@code null} if null array input
3375 */
3376 public static String join(Object[] array, String separator, int startIndex, int endIndex) {
3977 * @param startIndex the first index to start joining from.
3978 * @param endIndex the index to stop joining from (exclusive).
3979 * @return the joined String, {@code null} if null array input; or the empty string
3980 * if {@code endIndex - startIndex <= 0}. The number of joined entries is given by
3981 * {@code endIndex - startIndex}
3982 * @throws ArrayIndexOutOfBoundsException ife<br/>
3983 * {@code startIndex < 0} or <br/>
3984 * {@code startIndex >= array.length()} or <br/>
3985 * {@code endIndex < 0} or <br/>
3986 * {@code endIndex > array.length()}
3987 */
3988 public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
33773989 if (array == null) {
33783990 return null;
33793991 }
33833995
33843996 // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
33853997 // (Assuming that all Strings are roughly equally long)
3386 int noOfItems = endIndex - startIndex;
3998 final int noOfItems = endIndex - startIndex;
33873999 if (noOfItems <= 0) {
33884000 return EMPTY;
33894001 }
33904002
3391 StringBuilder buf = new StringBuilder(noOfItems * 16);
4003 final StringBuilder buf = new StringBuilder(noOfItems * 16);
33924004
33934005 for (int i = startIndex; i < endIndex; i++) {
33944006 if (i > startIndex) {
34154027 * @return the joined String, {@code null} if null iterator input
34164028 * @since 2.0
34174029 */
3418 public static String join(Iterator<?> iterator, char separator) {
4030 public static String join(final Iterator<?> iterator, final char separator) {
34194031
34204032 // handle null, zero and one elements before building a buffer
34214033 if (iterator == null) {
34244036 if (!iterator.hasNext()) {
34254037 return EMPTY;
34264038 }
3427 Object first = iterator.next();
4039 final Object first = iterator.next();
34284040 if (!iterator.hasNext()) {
34294041 return ObjectUtils.toString(first);
34304042 }
34314043
34324044 // two or more elements
3433 StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
4045 final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
34344046 if (first != null) {
34354047 buf.append(first);
34364048 }
34374049
34384050 while (iterator.hasNext()) {
34394051 buf.append(separator);
3440 Object obj = iterator.next();
4052 final Object obj = iterator.next();
34414053 if (obj != null) {
34424054 buf.append(obj);
34434055 }
34594071 * @param separator the separator character to use, null treated as ""
34604072 * @return the joined String, {@code null} if null iterator input
34614073 */
3462 public static String join(Iterator<?> iterator, String separator) {
4074 public static String join(final Iterator<?> iterator, final String separator) {
34634075
34644076 // handle null, zero and one elements before building a buffer
34654077 if (iterator == null) {
34684080 if (!iterator.hasNext()) {
34694081 return EMPTY;
34704082 }
3471 Object first = iterator.next();
4083 final Object first = iterator.next();
34724084 if (!iterator.hasNext()) {
34734085 return ObjectUtils.toString(first);
34744086 }
34754087
34764088 // two or more elements
3477 StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
4089 final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
34784090 if (first != null) {
34794091 buf.append(first);
34804092 }
34834095 if (separator != null) {
34844096 buf.append(separator);
34854097 }
3486 Object obj = iterator.next();
4098 final Object obj = iterator.next();
34874099 if (obj != null) {
34884100 buf.append(obj);
34894101 }
35054117 * @return the joined String, {@code null} if null iterator input
35064118 * @since 2.3
35074119 */
3508 public static String join(Iterable<?> iterable, char separator) {
4120 public static String join(final Iterable<?> iterable, final char separator) {
35094121 if (iterable == null) {
35104122 return null;
35114123 }
35264138 * @return the joined String, {@code null} if null iterator input
35274139 * @since 2.3
35284140 */
3529 public static String join(Iterable<?> iterable, String separator) {
4141 public static String join(final Iterable<?> iterable, final String separator) {
35304142 if (iterable == null) {
35314143 return null;
35324144 }
35494161 * @param str the String to delete whitespace from, may be null
35504162 * @return the String without whitespaces, {@code null} if null String input
35514163 */
3552 public static String deleteWhitespace(String str) {
4164 public static String deleteWhitespace(final String str) {
35534165 if (isEmpty(str)) {
35544166 return str;
35554167 }
3556 int sz = str.length();
3557 char[] chs = new char[sz];
4168 final int sz = str.length();
4169 final char[] chs = new char[sz];
35584170 int count = 0;
35594171 for (int i = 0; i < sz; i++) {
35604172 if (!Character.isWhitespace(str.charAt(i))) {
35934205 * {@code null} if null String input
35944206 * @since 2.1
35954207 */
3596 public static String removeStart(String str, String remove) {
4208 public static String removeStart(final String str, final String remove) {
35974209 if (isEmpty(str) || isEmpty(remove)) {
35984210 return str;
35994211 }
36284240 * {@code null} if null String input
36294241 * @since 2.4
36304242 */
3631 public static String removeStartIgnoreCase(String str, String remove) {
4243 public static String removeStartIgnoreCase(final String str, final String remove) {
36324244 if (isEmpty(str) || isEmpty(remove)) {
36334245 return str;
36344246 }
36624274 * {@code null} if null String input
36634275 * @since 2.1
36644276 */
3665 public static String removeEnd(String str, String remove) {
4277 public static String removeEnd(final String str, final String remove) {
36664278 if (isEmpty(str) || isEmpty(remove)) {
36674279 return str;
36684280 }
36984310 * {@code null} if null String input
36994311 * @since 2.4
37004312 */
3701 public static String removeEndIgnoreCase(String str, String remove) {
4313 public static String removeEndIgnoreCase(final String str, final String remove) {
37024314 if (isEmpty(str) || isEmpty(remove)) {
37034315 return str;
37044316 }
37314343 * {@code null} if null String input
37324344 * @since 2.1
37334345 */
3734 public static String remove(String str, String remove) {
4346 public static String remove(final String str, final String remove) {
37354347 if (isEmpty(str) || isEmpty(remove)) {
37364348 return str;
37374349 }
37574369 * {@code null} if null String input
37584370 * @since 2.1
37594371 */
3760 public static String remove(String str, char remove) {
4372 public static String remove(final String str, final char remove) {
37614373 if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
37624374 return str;
37634375 }
3764 char[] chars = str.toCharArray();
4376 final char[] chars = str.toCharArray();
37654377 int pos = 0;
37664378 for (int i = 0; i < chars.length; i++) {
37674379 if (chars[i] != remove) {
37964408 * @return the text with any replacements processed,
37974409 * {@code null} if null String input
37984410 */
3799 public static String replaceOnce(String text, String searchString, String replacement) {
4411 public static String replaceOnce(final String text, final String searchString, final String replacement) {
38004412 return replace(text, searchString, replacement, 1);
4413 }
4414
4415 /**
4416 * Replaces each substring of the source String that matches the given regular expression with the given
4417 * replacement using the {@link Pattern#DOTALL} option. DOTALL is also know as single-line mode in Perl. This call
4418 * is also equivalent to:
4419 * <ul>
4420 * <li>{@code source.replaceAll(&quot;(?s)&quot; + regex, replacement)}</li>
4421 * <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}</li>
4422 * </ul>
4423 *
4424 * @param source
4425 * the source string
4426 * @param regex
4427 * the regular expression to which this string is to be matched
4428 * @param replacement
4429 * the string to be substituted for each match
4430 * @return The resulting {@code String}
4431 * @see String#replaceAll(String, String)
4432 * @see Pattern#DOTALL
4433 * @since 3.2
4434 */
4435 public static String replacePattern(final String source, final String regex, final String replacement) {
4436 return Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement);
4437 }
4438
4439 /**
4440 * Removes each substring of the source String that matches the given regular expression using the DOTALL option.
4441 *
4442 * @param source
4443 * the source string
4444 * @param regex
4445 * the regular expression to which this string is to be matched
4446 * @return The resulting {@code String}
4447 * @see String#replaceAll(String, String)
4448 * @see Pattern#DOTALL
4449 * @since 3.2
4450 */
4451 public static String removePattern(final String source, final String regex) {
4452 return replacePattern(source, regex, StringUtils.EMPTY);
38014453 }
38024454
38034455 /**
38234475 * @return the text with any replacements processed,
38244476 * {@code null} if null String input
38254477 */
3826 public static String replace(String text, String searchString, String replacement) {
4478 public static String replace(final String text, final String searchString, final String replacement) {
38274479 return replace(text, searchString, replacement, -1);
38284480 }
38294481
38554507 * @return the text with any replacements processed,
38564508 * {@code null} if null String input
38574509 */
3858 public static String replace(String text, String searchString, String replacement, int max) {
4510 public static String replace(final String text, final String searchString, final String replacement, int max) {
38594511 if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
38604512 return text;
38614513 }
38644516 if (end == INDEX_NOT_FOUND) {
38654517 return text;
38664518 }
3867 int replLength = searchString.length();
4519 final int replLength = searchString.length();
38684520 int increase = replacement.length() - replLength;
38694521 increase = increase < 0 ? 0 : increase;
38704522 increase *= max < 0 ? 16 : max > 64 ? 64 : max;
3871 StringBuilder buf = new StringBuilder(text.length() + increase);
4523 final StringBuilder buf = new StringBuilder(text.length() + increase);
38724524 while (end != INDEX_NOT_FOUND) {
38734525 buf.append(text.substring(start, end)).append(replacement);
38744526 start = end + replLength;
39204572 * and/or size 0)
39214573 * @since 2.4
39224574 */
3923 public static String replaceEach(String text, String[] searchList, String[] replacementList) {
4575 public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {
39244576 return replaceEach(text, searchList, replacementList, false, 0);
39254577 }
39264578
39324584 * <p>
39334585 * A {@code null} reference passed to this method is a no-op, or if
39344586 * any "search string" or "string to replace" is null, that replace will be
3935 * ignored.
4587 * ignored.
39364588 * </p>
39374589 *
39384590 * <pre>
39684620 * and/or size 0)
39694621 * @since 2.4
39704622 */
3971 public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) {
4623 public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {
39724624 // timeToLive should be 0 if not used or nothing to replace, else it's
39734625 // the length of the replace array
3974 int timeToLive = searchList == null ? 0 : searchList.length;
4626 final int timeToLive = searchList == null ? 0 : searchList.length;
39754627 return replaceEach(text, searchList, replacementList, true, timeToLive);
39764628 }
39774629
40244676 * @since 2.4
40254677 */
40264678 private static String replaceEach(
4027 String text, String[] searchList, String[] replacementList, boolean repeat, int timeToLive) {
4679 final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {
40284680
40294681 // mchyzer Performance note: This creates very few new objects (one major goal)
40304682 // let me know if there are performance requests, we can create a harness to measure
40314683
4032 if (text == null || text.length() == 0 || searchList == null ||
4684 if (text == null || text.isEmpty() || searchList == null ||
40334685 searchList.length == 0 || replacementList == null || replacementList.length == 0) {
40344686 return text;
40354687 }
40404692 "output of one loop is the input of another");
40414693 }
40424694
4043 int searchLength = searchList.length;
4044 int replacementLength = replacementList.length;
4695 final int searchLength = searchList.length;
4696 final int replacementLength = replacementList.length;
40454697
40464698 // make sure lengths are ok, these need to be equal
40474699 if (searchLength != replacementLength) {
40524704 }
40534705
40544706 // keep track of which still have matches
4055 boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
4707 final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
40564708
40574709 // index on index that the match was found
40584710 int textIndex = -1;
40634715 // NOTE: logic duplicated below START
40644716 for (int i = 0; i < searchLength; i++) {
40654717 if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
4066 searchList[i].length() == 0 || replacementList[i] == null) {
4718 searchList[i].isEmpty() || replacementList[i] == null) {
40674719 continue;
40684720 }
40694721 tempIndex = text.indexOf(searchList[i]);
40954747 if (searchList[i] == null || replacementList[i] == null) {
40964748 continue;
40974749 }
4098 int greater = replacementList[i].length() - searchList[i].length();
4750 final int greater = replacementList[i].length() - searchList[i].length();
40994751 if (greater > 0) {
41004752 increase += 3 * greater; // assume 3 matches
41014753 }
41034755 // have upper-bound at 20% increase, then let Java take over
41044756 increase = Math.min(increase, text.length() / 5);
41054757
4106 StringBuilder buf = new StringBuilder(text.length() + increase);
4758 final StringBuilder buf = new StringBuilder(text.length() + increase);
41074759
41084760 while (textIndex != -1) {
41094761
41214773 // NOTE: logic mostly duplicated above START
41224774 for (int i = 0; i < searchLength; i++) {
41234775 if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
4124 searchList[i].length() == 0 || replacementList[i] == null) {
4776 searchList[i].isEmpty() || replacementList[i] == null) {
41254777 continue;
41264778 }
41274779 tempIndex = text.indexOf(searchList[i], start);
41394791 // NOTE: logic duplicated above END
41404792
41414793 }
4142 int textLength = text.length();
4794 final int textLength = text.length();
41434795 for (int i = start; i < textLength; i++) {
41444796 buf.append(text.charAt(i));
41454797 }
4146 String result = buf.toString();
4798 final String result = buf.toString();
41474799 if (!repeat) {
41484800 return result;
41494801 }
41734825 * @return modified String, {@code null} if null string input
41744826 * @since 2.0
41754827 */
4176 public static String replaceChars(String str, char searchChar, char replaceChar) {
4828 public static String replaceChars(final String str, final char searchChar, final char replaceChar) {
41774829 if (str == null) {
41784830 return null;
41794831 }
42164868 * @return modified String, {@code null} if null string input
42174869 * @since 2.0
42184870 */
4219 public static String replaceChars(String str, String searchChars, String replaceChars) {
4871 public static String replaceChars(final String str, final String searchChars, String replaceChars) {
42204872 if (isEmpty(str) || isEmpty(searchChars)) {
42214873 return str;
42224874 }
42244876 replaceChars = EMPTY;
42254877 }
42264878 boolean modified = false;
4227 int replaceCharsLength = replaceChars.length();
4228 int strLength = str.length();
4229 StringBuilder buf = new StringBuilder(strLength);
4879 final int replaceCharsLength = replaceChars.length();
4880 final int strLength = str.length();
4881 final StringBuilder buf = new StringBuilder(strLength);
42304882 for (int i = 0; i < strLength; i++) {
4231 char ch = str.charAt(i);
4232 int index = searchChars.indexOf(ch);
4883 final char ch = str.charAt(i);
4884 final int index = searchChars.indexOf(ch);
42334885 if (index >= 0) {
42344886 modified = true;
42354887 if (index < replaceCharsLength) {
42764928 * @return overlayed String, {@code null} if null String input
42774929 * @since 2.0
42784930 */
4279 public static String overlay(String str, String overlay, int start, int end) {
4931 public static String overlay(final String str, String overlay, int start, int end) {
42804932 if (str == null) {
42814933 return null;
42824934 }
42834935 if (overlay == null) {
42844936 overlay = EMPTY;
42854937 }
4286 int len = str.length();
4938 final int len = str.length();
42874939 if (start < 0) {
42884940 start = 0;
42894941 }
42974949 end = len;
42984950 }
42994951 if (start > end) {
4300 int temp = start;
4952 final int temp = start;
43014953 start = end;
43024954 end = temp;
43034955 }
43354987 * @param str the String to chomp a newline from, may be null
43364988 * @return String without newline, {@code null} if null String input
43374989 */
4338 public static String chomp(String str) {
4990 public static String chomp(final String str) {
43394991 if (isEmpty(str)) {
43404992 return str;
43414993 }
43424994
43434995 if (str.length() == 1) {
4344 char ch = str.charAt(0);
4996 final char ch = str.charAt(0);
43454997 if (ch == CharUtils.CR || ch == CharUtils.LF) {
43464998 return EMPTY;
43474999 }
43495001 }
43505002
43515003 int lastIdx = str.length() - 1;
4352 char last = str.charAt(lastIdx);
5004 final char last = str.charAt(lastIdx);
43535005
43545006 if (last == CharUtils.LF) {
43555007 if (str.charAt(lastIdx - 1) == CharUtils.CR) {
43895041 * @deprecated This feature will be removed in Lang 4.0, use {@link StringUtils#removeEnd(String, String)} instead
43905042 */
43915043 @Deprecated
4392 public static String chomp(String str, String separator) {
5044 public static String chomp(final String str, final String separator) {
43935045 return removeEnd(str,separator);
43945046 }
43955047
44185070 * @param str the String to chop last character from, may be null
44195071 * @return String without last character, {@code null} if null String input
44205072 */
4421 public static String chop(String str) {
5073 public static String chop(final String str) {
44225074 if (str == null) {
44235075 return null;
44245076 }
4425 int strLen = str.length();
5077 final int strLen = str.length();
44265078 if (strLen < 2) {
44275079 return EMPTY;
44285080 }
4429 int lastIdx = strLen - 1;
4430 String ret = str.substring(0, lastIdx);
4431 char last = str.charAt(lastIdx);
5081 final int lastIdx = strLen - 1;
5082 final String ret = str.substring(0, lastIdx);
5083 final char last = str.charAt(lastIdx);
44325084 if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) {
44335085 return ret.substring(0, lastIdx - 1);
44345086 }
44585110 * @return a new String consisting of the original String repeated,
44595111 * {@code null} if null String input
44605112 */
4461 public static String repeat(String str, int repeat) {
5113 public static String repeat(final String str, final int repeat) {
44625114 // Performance tuned for 2.0 (JDK1.4)
44635115
44645116 if (str == null) {
44675119 if (repeat <= 0) {
44685120 return EMPTY;
44695121 }
4470 int inputLength = str.length();
5122 final int inputLength = str.length();
44715123 if (repeat == 1 || inputLength == 0) {
44725124 return str;
44735125 }
44755127 return repeat(str.charAt(0), repeat);
44765128 }
44775129
4478 int outputLength = inputLength * repeat;
5130 final int outputLength = inputLength * repeat;
44795131 switch (inputLength) {
44805132 case 1 :
44815133 return repeat(str.charAt(0), repeat);
44825134 case 2 :
4483 char ch0 = str.charAt(0);
4484 char ch1 = str.charAt(1);
4485 char[] output2 = new char[outputLength];
5135 final char ch0 = str.charAt(0);
5136 final char ch1 = str.charAt(1);
5137 final char[] output2 = new char[outputLength];
44865138 for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
44875139 output2[i] = ch0;
44885140 output2[i + 1] = ch1;
44895141 }
44905142 return new String(output2);
44915143 default :
4492 StringBuilder buf = new StringBuilder(outputLength);
5144 final StringBuilder buf = new StringBuilder(outputLength);
44935145 for (int i = 0; i < repeat; i++) {
44945146 buf.append(str);
44955147 }
45175169 * {@code null} if null String input
45185170 * @since 2.5
45195171 */
4520 public static String repeat(String str, String separator, int repeat) {
5172 public static String repeat(final String str, final String separator, final int repeat) {
45215173 if(str == null || separator == null) {
45225174 return repeat(str, repeat);
4523 } else {
4524 // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
4525 String result = repeat(str + separator, repeat);
4526 return removeEnd(result, separator);
4527 }
5175 }
5176 // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
5177 final String result = repeat(str + separator, repeat);
5178 return removeEnd(result, separator);
45285179 }
45295180
45305181 /**
45325183 * to a given length.</p>
45335184 *
45345185 * <pre>
4535 * StringUtils.repeat(0, 'e') = ""
4536 * StringUtils.repeat(3, 'e') = "eee"
4537 * StringUtils.repeat(-2, 'e') = ""
5186 * StringUtils.repeat('e', 0) = ""
5187 * StringUtils.repeat('e', 3) = "eee"
5188 * StringUtils.repeat('e', -2) = ""
45385189 * </pre>
45395190 *
45405191 * <p>Note: this method doesn't not support padding with
45495200 * @return String with repeated character
45505201 * @see #repeat(String, int)
45515202 */
4552 public static String repeat(char ch, int repeat) {
4553 char[] buf = new char[repeat];
5203 public static String repeat(final char ch, final int repeat) {
5204 final char[] buf = new char[repeat];
45545205 for (int i = repeat - 1; i >= 0; i--) {
45555206 buf[i] = ch;
45565207 }
45765227 * @return right padded String or original String if no padding is necessary,
45775228 * {@code null} if null String input
45785229 */
4579 public static String rightPad(String str, int size) {
5230 public static String rightPad(final String str, final int size) {
45805231 return rightPad(str, size, ' ');
45815232 }
45825233
46015252 * {@code null} if null String input
46025253 * @since 2.0
46035254 */
4604 public static String rightPad(String str, int size, char padChar) {
5255 public static String rightPad(final String str, final int size, final char padChar) {
46055256 if (str == null) {
46065257 return null;
46075258 }
4608 int pads = size - str.length();
5259 final int pads = size - str.length();
46095260 if (pads <= 0) {
46105261 return str; // returns original String when possible
46115262 }
46385289 * @return right padded String or original String if no padding is necessary,
46395290 * {@code null} if null String input
46405291 */
4641 public static String rightPad(String str, int size, String padStr) {
5292 public static String rightPad(final String str, final int size, String padStr) {
46425293 if (str == null) {
46435294 return null;
46445295 }
46455296 if (isEmpty(padStr)) {
4646 padStr = " ";
4647 }
4648 int padLen = padStr.length();
4649 int strLen = str.length();
4650 int pads = size - strLen;
5297 padStr = SPACE;
5298 }
5299 final int padLen = padStr.length();
5300 final int strLen = str.length();
5301 final int pads = size - strLen;
46515302 if (pads <= 0) {
46525303 return str; // returns original String when possible
46535304 }
46605311 } else if (pads < padLen) {
46615312 return str.concat(padStr.substring(0, pads));
46625313 } else {
4663 char[] padding = new char[pads];
4664 char[] padChars = padStr.toCharArray();
5314 final char[] padding = new char[pads];
5315 final char[] padChars = padStr.toCharArray();
46655316 for (int i = 0; i < pads; i++) {
46665317 padding[i] = padChars[i % padLen];
46675318 }
46885339 * @return left padded String or original String if no padding is necessary,
46895340 * {@code null} if null String input
46905341 */
4691 public static String leftPad(String str, int size) {
5342 public static String leftPad(final String str, final int size) {
46925343 return leftPad(str, size, ' ');
46935344 }
46945345
47135364 * {@code null} if null String input
47145365 * @since 2.0
47155366 */
4716 public static String leftPad(String str, int size, char padChar) {
5367 public static String leftPad(final String str, final int size, final char padChar) {
47175368 if (str == null) {
47185369 return null;
47195370 }
4720 int pads = size - str.length();
5371 final int pads = size - str.length();
47215372 if (pads <= 0) {
47225373 return str; // returns original String when possible
47235374 }
47505401 * @return left padded String or original String if no padding is necessary,
47515402 * {@code null} if null String input
47525403 */
4753 public static String leftPad(String str, int size, String padStr) {
5404 public static String leftPad(final String str, final int size, String padStr) {
47545405 if (str == null) {
47555406 return null;
47565407 }
47575408 if (isEmpty(padStr)) {
4758 padStr = " ";
4759 }
4760 int padLen = padStr.length();
4761 int strLen = str.length();
4762 int pads = size - strLen;
5409 padStr = SPACE;
5410 }
5411 final int padLen = padStr.length();
5412 final int strLen = str.length();
5413 final int pads = size - strLen;
47635414 if (pads <= 0) {
47645415 return str; // returns original String when possible
47655416 }
47725423 } else if (pads < padLen) {
47735424 return padStr.substring(0, pads).concat(str);
47745425 } else {
4775 char[] padding = new char[pads];
4776 char[] padChars = padStr.toCharArray();
5426 final char[] padding = new char[pads];
5427 final char[] padChars = padStr.toCharArray();
47775428 for (int i = 0; i < pads; i++) {
47785429 padding[i] = padChars[i % padLen];
47795430 }
47925443 * @since 2.4
47935444 * @since 3.0 Changed signature from length(String) to length(CharSequence)
47945445 */
4795 public static int length(CharSequence cs) {
5446 public static int length(final CharSequence cs) {
47965447 return cs == null ? 0 : cs.length();
47975448 }
47985449
48215472 * @param size the int size of new String, negative treated as zero
48225473 * @return centered String, {@code null} if null String input
48235474 */
4824 public static String center(String str, int size) {
5475 public static String center(final String str, final int size) {
48255476 return center(str, size, ' ');
48265477 }
48275478
48375488 * StringUtils.center(null, *, *) = null
48385489 * StringUtils.center("", 4, ' ') = " "
48395490 * StringUtils.center("ab", -1, ' ') = "ab"
4840 * StringUtils.center("ab", 4, ' ') = " ab"
5491 * StringUtils.center("ab", 4, ' ') = " ab "
48415492 * StringUtils.center("abcd", 2, ' ') = "abcd"
48425493 * StringUtils.center("a", 4, ' ') = " a "
48435494 * StringUtils.center("a", 4, 'y') = "yayy"
48495500 * @return centered String, {@code null} if null String input
48505501 * @since 2.0
48515502 */
4852 public static String center(String str, int size, char padChar) {
5503 public static String center(String str, final int size, final char padChar) {
48535504 if (str == null || size <= 0) {
48545505 return str;
48555506 }
4856 int strLen = str.length();
4857 int pads = size - strLen;
5507 final int strLen = str.length();
5508 final int pads = size - strLen;
48585509 if (pads <= 0) {
48595510 return str;
48605511 }
48755526 * StringUtils.center(null, *, *) = null
48765527 * StringUtils.center("", 4, " ") = " "
48775528 * StringUtils.center("ab", -1, " ") = "ab"
4878 * StringUtils.center("ab", 4, " ") = " ab"
5529 * StringUtils.center("ab", 4, " ") = " ab "
48795530 * StringUtils.center("abcd", 2, " ") = "abcd"
48805531 * StringUtils.center("a", 4, " ") = " a "
48815532 * StringUtils.center("a", 4, "yz") = "yayz"
48895540 * @return centered String, {@code null} if null String input
48905541 * @throws IllegalArgumentException if padStr is {@code null} or empty
48915542 */
4892 public static String center(String str, int size, String padStr) {
5543 public static String center(String str, final int size, String padStr) {
48935544 if (str == null || size <= 0) {
48945545 return str;
48955546 }
48965547 if (isEmpty(padStr)) {
4897 padStr = " ";
4898 }
4899 int strLen = str.length();
4900 int pads = size - strLen;
5548 padStr = SPACE;
5549 }
5550 final int strLen = str.length();
5551 final int pads = size - strLen;
49015552 if (pads <= 0) {
49025553 return str;
49035554 }
49275578 * @param str the String to upper case, may be null
49285579 * @return the upper cased String, {@code null} if null String input
49295580 */
4930 public static String upperCase(String str) {
5581 public static String upperCase(final String str) {
49315582 if (str == null) {
49325583 return null;
49335584 }
49505601 * @return the upper cased String, {@code null} if null String input
49515602 * @since 2.5
49525603 */
4953 public static String upperCase(String str, Locale locale) {
5604 public static String upperCase(final String str, final Locale locale) {
49545605 if (str == null) {
49555606 return null;
49565607 }
49765627 * @param str the String to lower case, may be null
49775628 * @return the lower cased String, {@code null} if null String input
49785629 */
4979 public static String lowerCase(String str) {
5630 public static String lowerCase(final String str) {
49805631 if (str == null) {
49815632 return null;
49825633 }
49995650 * @return the lower cased String, {@code null} if null String input
50005651 * @since 2.5
50015652 */
5002 public static String lowerCase(String str, Locale locale) {
5653 public static String lowerCase(final String str, final Locale locale) {
50035654 if (str == null) {
50045655 return null;
50055656 }
50265677 * @see #uncapitalize(String)
50275678 * @since 2.0
50285679 */
5029 public static String capitalize(String str) {
5680 public static String capitalize(final String str) {
50305681 int strLen;
50315682 if (str == null || (strLen = str.length()) == 0) {
50325683 return str;
50335684 }
5685
5686 char firstChar = str.charAt(0);
5687 if (Character.isTitleCase(firstChar)) {
5688 // already capitalized
5689 return str;
5690 }
5691
50345692 return new StringBuilder(strLen)
5035 .append(Character.toTitleCase(str.charAt(0)))
5693 .append(Character.toTitleCase(firstChar))
50365694 .append(str.substring(1))
50375695 .toString();
50385696 }
50575715 * @see #capitalize(String)
50585716 * @since 2.0
50595717 */
5060 public static String uncapitalize(String str) {
5718 public static String uncapitalize(final String str) {
50615719 int strLen;
50625720 if (str == null || (strLen = str.length()) == 0) {
50635721 return str;
50645722 }
5723
5724 char firstChar = str.charAt(0);
5725 if (Character.isLowerCase(firstChar)) {
5726 // already uncapitalized
5727 return str;
5728 }
5729
50655730 return new StringBuilder(strLen)
5066 .append(Character.toLowerCase(str.charAt(0)))
5731 .append(Character.toLowerCase(firstChar))
50675732 .append(str.substring(1))
50685733 .toString();
50695734 }
50955760 * @param str the String to swap case, may be null
50965761 * @return the changed String, {@code null} if null String input
50975762 */
5098 public static String swapCase(String str) {
5763 public static String swapCase(final String str) {
50995764 if (StringUtils.isEmpty(str)) {
51005765 return str;
51015766 }
51025767
5103 char[] buffer = str.toCharArray();
5768 final char[] buffer = str.toCharArray();
51045769
51055770 for (int i = 0; i < buffer.length; i++) {
5106 char ch = buffer[i];
5771 final char ch = buffer[i];
51075772 if (Character.isUpperCase(ch)) {
51085773 buffer[i] = Character.toLowerCase(ch);
51095774 } else if (Character.isTitleCase(ch)) {
51375802 * @return the number of occurrences, 0 if either CharSequence is {@code null}
51385803 * @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence)
51395804 */
5140 public static int countMatches(CharSequence str, CharSequence sub) {
5805 public static int countMatches(final CharSequence str, final CharSequence sub) {
51415806 if (isEmpty(str) || isEmpty(sub)) {
51425807 return 0;
51435808 }
51725837 * @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence)
51735838 * @since 3.0 Changed "" to return false and not true
51745839 */
5175 public static boolean isAlpha(CharSequence cs) {
5176 if (cs == null || cs.length() == 0) {
5840 public static boolean isAlpha(final CharSequence cs) {
5841 if (isEmpty(cs)) {
51775842 return false;
51785843 }
5179 int sz = cs.length();
5844 final int sz = cs.length();
51805845 for (int i = 0; i < sz; i++) {
51815846 if (Character.isLetter(cs.charAt(i)) == false) {
51825847 return false;
52075872 * and is non-null
52085873 * @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence)
52095874 */
5210 public static boolean isAlphaSpace(CharSequence cs) {
5875 public static boolean isAlphaSpace(final CharSequence cs) {
52115876 if (cs == null) {
52125877 return false;
52135878 }
5214 int sz = cs.length();
5879 final int sz = cs.length();
52155880 for (int i = 0; i < sz; i++) {
52165881 if (Character.isLetter(cs.charAt(i)) == false && cs.charAt(i) != ' ') {
52175882 return false;
52425907 * @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence)
52435908 * @since 3.0 Changed "" to return false and not true
52445909 */
5245 public static boolean isAlphanumeric(CharSequence cs) {
5246 if (cs == null || cs.length() == 0) {
5910 public static boolean isAlphanumeric(final CharSequence cs) {
5911 if (isEmpty(cs)) {
52475912 return false;
52485913 }
5249 int sz = cs.length();
5914 final int sz = cs.length();
52505915 for (int i = 0; i < sz; i++) {
52515916 if (Character.isLetterOrDigit(cs.charAt(i)) == false) {
52525917 return false;
52775942 * and is non-null
52785943 * @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence)
52795944 */
5280 public static boolean isAlphanumericSpace(CharSequence cs) {
5945 public static boolean isAlphanumericSpace(final CharSequence cs) {
52815946 if (cs == null) {
52825947 return false;
52835948 }
5284 int sz = cs.length();
5949 final int sz = cs.length();
52855950 for (int i = 0; i < sz; i++) {
52865951 if (Character.isLetterOrDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') {
52875952 return false;
53165981 * @since 2.1
53175982 * @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence)
53185983 */
5319 public static boolean isAsciiPrintable(CharSequence cs) {
5984 public static boolean isAsciiPrintable(final CharSequence cs) {
53205985 if (cs == null) {
53215986 return false;
53225987 }
5323 int sz = cs.length();
5988 final int sz = cs.length();
53245989 for (int i = 0; i < sz; i++) {
53255990 if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) {
53265991 return false;
53356000 *
53366001 * <p>{@code null} will return {@code false}.
53376002 * An empty CharSequence (length()=0) will return {@code false}.</p>
6003 *
6004 * <p>Note that the method does not allow for a leading sign, either positive or negative.
6005 * Also, if a String passes the numeric test, it may still generate a NumberFormatException
6006 * when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range
6007 * for int or long respectively.</p>
53386008 *
53396009 * <pre>
53406010 * StringUtils.isNumeric(null) = false
53456015 * StringUtils.isNumeric("ab2c") = false
53466016 * StringUtils.isNumeric("12-3") = false
53476017 * StringUtils.isNumeric("12.3") = false
6018 * StringUtils.isNumeric("-123") = false
6019 * StringUtils.isNumeric("+123") = false
53486020 * </pre>
53496021 *
53506022 * @param cs the CharSequence to check, may be null
53526024 * @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)
53536025 * @since 3.0 Changed "" to return false and not true
53546026 */
5355 public static boolean isNumeric(CharSequence cs) {
5356 if (cs == null || cs.length() == 0) {
6027 public static boolean isNumeric(final CharSequence cs) {
6028 if (isEmpty(cs)) {
53576029 return false;
53586030 }
5359 int sz = cs.length();
6031 final int sz = cs.length();
53606032 for (int i = 0; i < sz; i++) {
53616033 if (Character.isDigit(cs.charAt(i)) == false) {
53626034 return false;
53896061 * and is non-null
53906062 * @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence)
53916063 */
5392 public static boolean isNumericSpace(CharSequence cs) {
6064 public static boolean isNumericSpace(final CharSequence cs) {
53936065 if (cs == null) {
53946066 return false;
53956067 }
5396 int sz = cs.length();
6068 final int sz = cs.length();
53976069 for (int i = 0; i < sz; i++) {
53986070 if (Character.isDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') {
53996071 return false;
54226094 * @since 2.0
54236095 * @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence)
54246096 */
5425 public static boolean isWhitespace(CharSequence cs) {
6097 public static boolean isWhitespace(final CharSequence cs) {
54266098 if (cs == null) {
54276099 return false;
54286100 }
5429 int sz = cs.length();
6101 final int sz = cs.length();
54306102 for (int i = 0; i < sz; i++) {
54316103 if (Character.isWhitespace(cs.charAt(i)) == false) {
54326104 return false;
54546126 * @since 2.5
54556127 * @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence)
54566128 */
5457 public static boolean isAllLowerCase(CharSequence cs) {
6129 public static boolean isAllLowerCase(final CharSequence cs) {
54586130 if (cs == null || isEmpty(cs)) {
54596131 return false;
54606132 }
5461 int sz = cs.length();
6133 final int sz = cs.length();
54626134 for (int i = 0; i < sz; i++) {
54636135 if (Character.isLowerCase(cs.charAt(i)) == false) {
54646136 return false;
54866158 * @since 2.5
54876159 * @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence)
54886160 */
5489 public static boolean isAllUpperCase(CharSequence cs) {
6161 public static boolean isAllUpperCase(final CharSequence cs) {
54906162 if (cs == null || isEmpty(cs)) {
54916163 return false;
54926164 }
5493 int sz = cs.length();
6165 final int sz = cs.length();
54946166 for (int i = 0; i < sz; i++) {
54956167 if (Character.isUpperCase(cs.charAt(i)) == false) {
54966168 return false;
55176189 * @return the passed in String, or the empty String if it
55186190 * was {@code null}
55196191 */
5520 public static String defaultString(String str) {
6192 public static String defaultString(final String str) {
55216193 return str == null ? EMPTY : str;
55226194 }
55236195
55386210 * if the input is {@code null}, may be null
55396211 * @return the passed in String, or the default if it was {@code null}
55406212 */
5541 public static String defaultString(String str, String defaultStr) {
6213 public static String defaultString(final String str, final String defaultStr) {
55426214 return str == null ? defaultStr : str;
55436215 }
55446216
55606232 * @return the passed in CharSequence, or the default
55616233 * @see StringUtils#defaultString(String, String)
55626234 */
5563 public static <T extends CharSequence> T defaultIfBlank(T str, T defaultStr) {
6235 public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) {
55646236 return StringUtils.isBlank(str) ? defaultStr : str;
55656237 }
55666238
55826254 * @return the passed in CharSequence, or the default
55836255 * @see StringUtils#defaultString(String, String)
55846256 */
5585 public static <T extends CharSequence> T defaultIfEmpty(T str, T defaultStr) {
6257 public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr) {
55866258 return StringUtils.isEmpty(str) ? defaultStr : str;
55876259 }
55886260
56026274 * @param str the String to reverse, may be null
56036275 * @return the reversed String, {@code null} if null String input
56046276 */
5605 public static String reverse(String str) {
6277 public static String reverse(final String str) {
56066278 if (str == null) {
56076279 return null;
56086280 }
56286300 * @return the reversed String, {@code null} if null String input
56296301 * @since 2.0
56306302 */
5631 public static String reverseDelimited(String str, char separatorChar) {
6303 public static String reverseDelimited(final String str, final char separatorChar) {
56326304 if (str == null) {
56336305 return null;
56346306 }
56356307 // could implement manually, but simple way is to reuse other,
56366308 // probably slower, methods.
5637 String[] strs = split(str, separatorChar);
6309 final String[] strs = split(str, separatorChar);
56386310 ArrayUtils.reverse(strs);
56396311 return join(strs, separatorChar);
56406312 }
56736345 * @throws IllegalArgumentException if the width is too small
56746346 * @since 2.0
56756347 */
5676 public static String abbreviate(String str, int maxWidth) {
6348 public static String abbreviate(final String str, final int maxWidth) {
56776349 return abbreviate(str, 0, maxWidth);
56786350 }
56796351
57126384 * @throws IllegalArgumentException if the width is too small
57136385 * @since 2.0
57146386 */
5715 public static String abbreviate(String str, int offset, int maxWidth) {
6387 public static String abbreviate(final String str, int offset, final int maxWidth) {
57166388 if (str == null) {
57176389 return null;
57186390 }
57706442 * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
57716443 * @since 2.5
57726444 */
5773 public static String abbreviateMiddle(String str, String middle, int length) {
6445 public static String abbreviateMiddle(final String str, final String middle, final int length) {
57746446 if (isEmpty(str) || isEmpty(middle)) {
57756447 return str;
57766448 }
57796451 return str;
57806452 }
57816453
5782 int targetSting = length-middle.length();
5783 int startOffset = targetSting/2+targetSting%2;
5784 int endOffset = str.length()-targetSting/2;
5785
5786 StringBuilder builder = new StringBuilder(length);
6454 final int targetSting = length-middle.length();
6455 final int startOffset = targetSting/2+targetSting%2;
6456 final int endOffset = str.length()-targetSting/2;
6457
6458 final StringBuilder builder = new StringBuilder(length);
57876459 builder.append(str.substring(0,startOffset));
57886460 builder.append(middle);
57896461 builder.append(str.substring(endOffset));
57956467 //-----------------------------------------------------------------------
57966468 /**
57976469 * <p>Compares two Strings, and returns the portion where they differ.
5798 * (More precisely, return the remainder of the second String,
5799 * starting from where it's different from the first.)</p>
6470 * More precisely, return the remainder of the second String,
6471 * starting from where it's different from the first. This means that
6472 * the difference between "abc" and "ab" is the empty String and not "c". </p>
58006473 *
58016474 * <p>For example,
58026475 * {@code difference("i am a machine", "i am a robot") -> "robot"}.</p>
58076480 * StringUtils.difference("", "abc") = "abc"
58086481 * StringUtils.difference("abc", "") = ""
58096482 * StringUtils.difference("abc", "abc") = ""
6483 * StringUtils.difference("abc", "ab") = ""
58106484 * StringUtils.difference("ab", "abxyz") = "xyz"
58116485 * StringUtils.difference("abcde", "abxyz") = "xyz"
58126486 * StringUtils.difference("abcde", "xyz") = "xyz"
58166490 * @param str2 the second String, may be null
58176491 * @return the portion of str2 where it differs from str1; returns the
58186492 * empty String if they are equal
6493 * @see #indexOfDifference(CharSequence,CharSequence)
58196494 * @since 2.0
58206495 */
5821 public static String difference(String str1, String str2) {
6496 public static String difference(final String str1, final String str2) {
58226497 if (str1 == null) {
58236498 return str2;
58246499 }
58256500 if (str2 == null) {
58266501 return str1;
58276502 }
5828 int at = indexOfDifference(str1, str2);
6503 final int at = indexOfDifference(str1, str2);
58296504 if (at == INDEX_NOT_FOUND) {
58306505 return EMPTY;
58316506 }
58576532 * @since 3.0 Changed signature from indexOfDifference(String, String) to
58586533 * indexOfDifference(CharSequence, CharSequence)
58596534 */
5860 public static int indexOfDifference(CharSequence cs1, CharSequence cs2) {
6535 public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) {
58616536 if (cs1 == cs2) {
58626537 return INDEX_NOT_FOUND;
58636538 }
59086583 * @since 2.4
59096584 * @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...)
59106585 */
5911 public static int indexOfDifference(CharSequence... css) {
6586 public static int indexOfDifference(final CharSequence... css) {
59126587 if (css == null || css.length <= 1) {
59136588 return INDEX_NOT_FOUND;
59146589 }
59156590 boolean anyStringNull = false;
59166591 boolean allStringsNull = true;
5917 int arrayLen = css.length;
6592 final int arrayLen = css.length;
59186593 int shortestStrLen = Integer.MAX_VALUE;
59196594 int longestStrLen = 0;
59206595
59456620 // find the position with the first difference across all strings
59466621 int firstDiff = -1;
59476622 for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
5948 char comparisonChar = css[0].charAt(stringPos);
6623 final char comparisonChar = css[0].charAt(stringPos);
59496624 for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
59506625 if (css[arrayPos].charAt(stringPos) != comparisonChar) {
59516626 firstDiff = stringPos;
59996674 * or if there is no common prefix.
60006675 * @since 2.4
60016676 */
6002 public static String getCommonPrefix(String... strs) {
6677 public static String getCommonPrefix(final String... strs) {
60036678 if (strs == null || strs.length == 0) {
60046679 return EMPTY;
60056680 }
6006 int smallestIndexOfDiff = indexOfDifference(strs);
6681 final int smallestIndexOfDiff = indexOfDifference(strs);
60076682 if (smallestIndexOfDiff == INDEX_NOT_FOUND) {
60086683 // all strings were identical
60096684 if (strs[0] == null) {
60906765
60916766 if (n > m) {
60926767 // swap the input strings to consume less memory
6093 CharSequence tmp = s;
6768 final CharSequence tmp = s;
60946769 s = t;
60956770 t = tmp;
60966771 n = m;
61356810 }
61366811
61376812 /**
6138 * <p>Find the Levenshtein distance between two Strings if it's less than or equal to a given
6813 * <p>Find the Levenshtein distance between two Strings if it's less than or equal to a given
61396814 * threshold.</p>
61406815 *
61416816 * <p>This is the number of changes needed to change one String into
61666841 * @return result distance, or {@code -1} if the distance would be greater than the threshold
61676842 * @throws IllegalArgumentException if either String input {@code null} or negative threshold
61686843 */
6169 public static int getLevenshteinDistance(CharSequence s, CharSequence t, int threshold) {
6844 public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) {
61706845 if (s == null || t == null) {
61716846 throw new IllegalArgumentException("Strings must not be null");
61726847 }
61776852 /*
61786853 This implementation only computes the distance if it's less than or equal to the
61796854 threshold value, returning -1 if it's greater. The advantage is performance: unbounded
6180 distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only
6855 distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only
61816856 computing a diagonal stripe of width 2k + 1 of the cost table.
61826857 It is also possible to use this to compute the unbounded Levenshtein distance by starting
61836858 the threshold at 1 and doubling each time until the distance is found; this is O(dm), where
61846859 d is the distance.
6185
6860
61866861 One subtlety comes from needing to ignore entries on the border of our stripe
61876862 eg.
61886863 p[] = |#|#|#|*
61896864 d[] = *|#|#|#|
61906865 We must ignore the entry to the left of the leftmost member
61916866 We must ignore the entry above the rightmost member
6192
6867
61936868 Another subtlety comes from our stripe running off the matrix if the strings aren't
6194 of the same size. Since string s is always swapped to be the shorter of the two,
6869 of the same size. Since string s is always swapped to be the shorter of the two,
61956870 the stripe will always run off to the upper right instead of the lower left of the matrix.
6196
6871
61976872 As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1.
61986873 In this case we're going to walk a stripe of length 3. The matrix would look like so:
6199
6874
62006875 1 2 3 4 5
62016876 1 |#|#| | | |
62026877 2 |#|#|#| | |
62086883
62096884 Note how the stripe leads off the table as there is no possible way to turn a string of length 5
62106885 into one of length 7 in edit distance of 1.
6211
6212 Additionally, this implementation decreases memory usage by using two
6886
6887 Additionally, this implementation decreases memory usage by using two
62136888 single-dimensional arrays and swapping them back and forth instead of allocating
6214 an entire n by m matrix. This requires a few minor changes, such as immediately returning
6889 an entire n by m matrix. This requires a few minor changes, such as immediately returning
62156890 when it's detected that the stripe has run off the matrix and initially filling the arrays with
62166891 large values so that entries we don't compute are ignored.
62176892
62306905
62316906 if (n > m) {
62326907 // swap the two strings to consume less memory
6233 CharSequence tmp = s;
6908 final CharSequence tmp = s;
62346909 s = t;
62356910 t = tmp;
62366911 n = m;
62426917 int _d[]; // placeholder to assist in swapping p and d
62436918
62446919 // fill in starting table values
6245 int boundary = Math.min(n, threshold) + 1;
6920 final int boundary = Math.min(n, threshold) + 1;
62466921 for (int i = 0; i < boundary; i++) {
62476922 p[i] = i;
62486923 }
6249 // these fills ensure that the value above the rightmost entry of our
6924 // these fills ensure that the value above the rightmost entry of our
62506925 // stripe will be ignored in following loop iterations
62516926 Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
62526927 Arrays.fill(d, Integer.MAX_VALUE);
62536928
62546929 // iterates through t
62556930 for (int j = 1; j <= m; j++) {
6256 char t_j = t.charAt(j - 1); // jth character of t
6931 final char t_j = t.charAt(j - 1); // jth character of t
62576932 d[0] = j;
62586933
62596934 // compute stripe indices, constrain to array size
6260 int min = Math.max(1, j - threshold);
6261 int max = Math.min(n, j + threshold);
6935 final int min = Math.max(1, j - threshold);
6936 final int max = Math.min(n, j + threshold);
62626937
62636938 // the stripe may lead off of the table if s and t are of different sizes
62646939 if (min > max) {
62916966 // distance
62926967 if (p[n] <= threshold) {
62936968 return p[n];
6294 } else {
6295 return -1;
6296 }
6969 }
6970 return -1;
62976971 }
62986972
62996973 // startsWith
63216995 * @since 2.4
63226996 * @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence)
63236997 */
6324 public static boolean startsWith(CharSequence str, CharSequence prefix) {
6998 public static boolean startsWith(final CharSequence str, final CharSequence prefix) {
63256999 return startsWith(str, prefix, false);
63267000 }
63277001
63477021 * @since 2.4
63487022 * @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence)
63497023 */
6350 public static boolean startsWithIgnoreCase(CharSequence str, CharSequence prefix) {
7024 public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) {
63517025 return startsWith(str, prefix, true);
63527026 }
63537027
63627036 * @return {@code true} if the CharSequence starts with the prefix or
63637037 * both {@code null}
63647038 */
6365 private static boolean startsWith(CharSequence str, CharSequence prefix, boolean ignoreCase) {
7039 private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) {
63667040 if (str == null || prefix == null) {
63677041 return str == null && prefix == null;
63687042 }
63917065 * @since 2.5
63927066 * @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...)
63937067 */
6394 public static boolean startsWithAny(CharSequence string, CharSequence... searchStrings) {
7068 public static boolean startsWithAny(final CharSequence string, final CharSequence... searchStrings) {
63957069 if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
63967070 return false;
63977071 }
6398 for (CharSequence searchString : searchStrings) {
7072 for (final CharSequence searchString : searchStrings) {
63997073 if (StringUtils.startsWith(string, searchString)) {
64007074 return true;
64017075 }
64297103 * @since 2.4
64307104 * @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence)
64317105 */
6432 public static boolean endsWith(CharSequence str, CharSequence suffix) {
7106 public static boolean endsWith(final CharSequence str, final CharSequence suffix) {
64337107 return endsWith(str, suffix, false);
64347108 }
64357109
64567130 * @since 2.4
64577131 * @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence)
64587132 */
6459 public static boolean endsWithIgnoreCase(CharSequence str, CharSequence suffix) {
7133 public static boolean endsWithIgnoreCase(final CharSequence str, final CharSequence suffix) {
64607134 return endsWith(str, suffix, true);
64617135 }
64627136
64717145 * @return {@code true} if the CharSequence starts with the prefix or
64727146 * both {@code null}
64737147 */
6474 private static boolean endsWith(CharSequence str, CharSequence suffix, boolean ignoreCase) {
7148 private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) {
64757149 if (str == null || suffix == null) {
64767150 return str == null && suffix == null;
64777151 }
64787152 if (suffix.length() > str.length()) {
64797153 return false;
64807154 }
6481 int strOffset = str.length() - suffix.length();
7155 final int strOffset = str.length() - suffix.length();
64827156 return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length());
64837157 }
64847158
65237197 *
65247198 * @since 3.0
65257199 */
6526 public static String normalizeSpace(String str) {
7200 public static String normalizeSpace(final String str) {
65277201 if (str == null) {
65287202 return null;
65297203 }
6530 return WHITESPACE_BLOCK.matcher(trim(str)).replaceAll(" ");
7204 return WHITESPACE_PATTERN.matcher(trim(str)).replaceAll(SPACE);
65317205 }
65327206
65337207 /**
65487222 * both {@code null}
65497223 * @since 3.0
65507224 */
6551 public static boolean endsWithAny(CharSequence string, CharSequence... searchStrings) {
7225 public static boolean endsWithAny(final CharSequence string, final CharSequence... searchStrings) {
65527226 if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
65537227 return false;
65547228 }
6555 for (CharSequence searchString : searchStrings) {
7229 for (final CharSequence searchString : searchStrings) {
65567230 if (StringUtils.endsWith(string, searchString)) {
65577231 return true;
65587232 }
65617235 }
65627236
65637237 /**
7238 * Appends the suffix to the end of the string if the string does not
7239 * already end in the suffix.
7240 *
7241 * @param str The string.
7242 * @param suffix The suffix to append to the end of the string.
7243 * @param ignoreCase Indicates whether the compare should ignore case.
7244 * @param suffixes Additional suffixes that are valid terminators (optional).
7245 *
7246 * @return A new String if suffix was appened, the same string otherwise.
7247 */
7248 private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) {
7249 if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) {
7250 return str;
7251 }
7252 if (suffixes != null && suffixes.length > 0) {
7253 for (final CharSequence s : suffixes) {
7254 if (endsWith(str, s, ignoreCase)) {
7255 return str;
7256 }
7257 }
7258 }
7259 return str + suffix.toString();
7260 }
7261
7262 /**
7263 * Appends the suffix to the end of the string if the string does not
7264 * already end with any the suffixes.
7265 *
7266 * <pre>
7267 * StringUtils.appendIfMissing(null, null) = null
7268 * StringUtils.appendIfMissing("abc", null) = "abc"
7269 * StringUtils.appendIfMissing("", "xyz") = "xyz"
7270 * StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
7271 * StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
7272 * StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
7273 * </pre>
7274 * <p>With additional suffixes,</p>
7275 * <pre>
7276 * StringUtils.appendIfMissing(null, null, null) = null
7277 * StringUtils.appendIfMissing("abc", null, null) = "abc"
7278 * StringUtils.appendIfMissing("", "xyz", null) = "xyz"
7279 * StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
7280 * StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
7281 * StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
7282 * StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
7283 * StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
7284 * StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
7285 * StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
7286 * </pre>
7287 *
7288 * @param str The string.
7289 * @param suffix The suffix to append to the end of the string.
7290 * @param suffixes Additional suffixes that are valid terminators.
7291 *
7292 * @return A new String if suffix was appened, the same string otherwise.
7293 *
7294 * @since 3.2
7295 */
7296 public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) {
7297 return appendIfMissing(str, suffix, false, suffixes);
7298 }
7299
7300 /**
7301 * Appends the suffix to the end of the string if the string does not
7302 * already end, case insensitive, with any of the suffixes.
7303 *
7304 * <pre>
7305 * StringUtils.appendIfMissingIgnoreCase(null, null) = null
7306 * StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
7307 * StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
7308 * StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
7309 * StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
7310 * StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
7311 * </pre>
7312 * <p>With additional suffixes,</p>
7313 * <pre>
7314 * StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
7315 * StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
7316 * StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
7317 * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
7318 * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
7319 * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz"
7320 * StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
7321 * StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
7322 * StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
7323 * StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
7324 * </pre>
7325 *
7326 * @param str The string.
7327 * @param suffix The suffix to append to the end of the string.
7328 * @param suffixes Additional suffixes that are valid terminators.
7329 *
7330 * @return A new String if suffix was appened, the same string otherwise.
7331 *
7332 * @since 3.2
7333 */
7334 public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) {
7335 return appendIfMissing(str, suffix, true, suffixes);
7336 }
7337
7338 /**
7339 * Prepends the prefix to the start of the string if the string does not
7340 * already start with any of the prefixes.
7341 *
7342 * @param str The string.
7343 * @param prefix The prefix to prepend to the start of the string.
7344 * @param ignoreCase Indicates whether the compare should ignore case.
7345 * @param prefixes Additional prefixes that are valid (optional).
7346 *
7347 * @return A new String if prefix was prepended, the same string otherwise.
7348 */
7349 private static String prependIfMissing(final String str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes) {
7350 if (str == null || isEmpty(prefix) || startsWith(str, prefix, ignoreCase)) {
7351 return str;
7352 }
7353 if (prefixes != null && prefixes.length > 0) {
7354 for (final CharSequence p : prefixes) {
7355 if (startsWith(str, p, ignoreCase)) {
7356 return str;
7357 }
7358 }
7359 }
7360 return prefix.toString() + str;
7361 }
7362
7363 /**
7364 * Prepends the prefix to the start of the string if the string does not
7365 * already start with any of the prefixes.
7366 *
7367 * <pre>
7368 * StringUtils.prependIfMissing(null, null) = null
7369 * StringUtils.prependIfMissing("abc", null) = "abc"
7370 * StringUtils.prependIfMissing("", "xyz") = "xyz"
7371 * StringUtils.prependIfMissing("abc", "xyz") = "xyzabc"
7372 * StringUtils.prependIfMissing("xyzabc", "xyz") = "xyzabc"
7373 * StringUtils.prependIfMissing("XYZabc", "xyz") = "xyzXYZabc"
7374 * </pre>
7375 * <p>With additional prefixes,</p>
7376 * <pre>
7377 * StringUtils.prependIfMissing(null, null, null) = null
7378 * StringUtils.prependIfMissing("abc", null, null) = "abc"
7379 * StringUtils.prependIfMissing("", "xyz", null) = "xyz"
7380 * StringUtils.prependIfMissing("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
7381 * StringUtils.prependIfMissing("abc", "xyz", "") = "abc"
7382 * StringUtils.prependIfMissing("abc", "xyz", "mno") = "xyzabc"
7383 * StringUtils.prependIfMissing("xyzabc", "xyz", "mno") = "xyzabc"
7384 * StringUtils.prependIfMissing("mnoabc", "xyz", "mno") = "mnoabc"
7385 * StringUtils.prependIfMissing("XYZabc", "xyz", "mno") = "xyzXYZabc"
7386 * StringUtils.prependIfMissing("MNOabc", "xyz", "mno") = "xyzMNOabc"
7387 * </pre>
7388 *
7389 * @param str The string.
7390 * @param prefix The prefix to prepend to the start of the string.
7391 * @param prefixes Additional prefixes that are valid.
7392 *
7393 * @return A new String if prefix was prepended, the same string otherwise.
7394 *
7395 * @since 3.2
7396 */
7397 public static String prependIfMissing(final String str, final CharSequence prefix, final CharSequence... prefixes) {
7398 return prependIfMissing(str, prefix, false, prefixes);
7399 }
7400
7401 /**
7402 * Prepends the prefix to the start of the string if the string does not
7403 * already start, case insensitive, with any of the prefixes.
7404 *
7405 * <pre>
7406 * StringUtils.prependIfMissingIgnoreCase(null, null) = null
7407 * StringUtils.prependIfMissingIgnoreCase("abc", null) = "abc"
7408 * StringUtils.prependIfMissingIgnoreCase("", "xyz") = "xyz"
7409 * StringUtils.prependIfMissingIgnoreCase("abc", "xyz") = "xyzabc"
7410 * StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz") = "xyzabc"
7411 * StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz") = "XYZabc"
7412 * </pre>
7413 * <p>With additional prefixes,</p>
7414 * <pre>
7415 * StringUtils.prependIfMissingIgnoreCase(null, null, null) = null
7416 * StringUtils.prependIfMissingIgnoreCase("abc", null, null) = "abc"
7417 * StringUtils.prependIfMissingIgnoreCase("", "xyz", null) = "xyz"
7418 * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
7419 * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "") = "abc"
7420 * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno") = "xyzabc"
7421 * StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno") = "xyzabc"
7422 * StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno") = "mnoabc"
7423 * StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno") = "XYZabc"
7424 * StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno") = "MNOabc"
7425 * </pre>
7426 *
7427 * @param str The string.
7428 * @param prefix The prefix to prepend to the start of the string.
7429 * @param prefixes Additional prefixes that are valid (optional).
7430 *
7431 * @return A new String if prefix was prepended, the same string otherwise.
7432 *
7433 * @since 3.2
7434 */
7435 public static String prependIfMissingIgnoreCase(final String str, final CharSequence prefix, final CharSequence... prefixes) {
7436 return prependIfMissing(str, prefix, true, prefixes);
7437 }
7438
7439 /**
65647440 * Converts a <code>byte[]</code> to a String using the specified character encoding.
6565 *
7441 *
65667442 * @param bytes
65677443 * the byte array to read from
65687444 * @param charsetName
65727448 * If the named charset is not supported
65737449 * @throws NullPointerException
65747450 * if the input is null
7451 * @deprecated use {@link StringUtils#toEncodedString(byte[], Charset)} instead of String constants in your code
65757452 * @since 3.1
65767453 */
6577 public static String toString(byte[] bytes, String charsetName) throws UnsupportedEncodingException {
6578 return charsetName == null ? new String(bytes) : new String(bytes, charsetName);
7454 @Deprecated
7455 public static String toString(final byte[] bytes, final String charsetName) throws UnsupportedEncodingException {
7456 return charsetName != null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset());
7457 }
7458
7459 /**
7460 * Converts a <code>byte[]</code> to a String using the specified character encoding.
7461 *
7462 * @param bytes
7463 * the byte array to read from
7464 * @param charset
7465 * the encoding to use, if null then use the platform default
7466 * @return a new String
7467 * @throws UnsupportedEncodingException
7468 * If the named charset is not supported
7469 * @throws NullPointerException
7470 * if the input is null
7471 * @since 3.2
7472 */
7473 public static String toEncodedString(byte[] bytes, Charset charset) throws UnsupportedEncodingException {
7474 return new String(bytes, charset != null ? charset : Charset.defaultCharset());
65797475 }
65807476
65817477 }
3030 * </p>
3131 *
3232 * @since 1.0
33 * @version $Id: SystemUtils.java 1199816 2011-11-09 16:11:34Z bayard $
33 * @version $Id: SystemUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3434 */
3535 public class SystemUtils {
3636
111111
112112 /**
113113 * <p>
114 * The {@code file.separator} System Property. File separator (<code>&quot;/&quot;</code> on UNIX).
114 * The {@code file.separator} System Property.
115 * The file separator is:
116 * <ul>
117 * <li>{@code "/"}</code> on UNIX</li>
118 * <li>{@code "\"}</code> on Windows.</li>
119 * </ul>
115120 * </p>
116121 * <p>
117122 * Defaults to {@code null} if the runtime does not have security access to read this property or the property does
12241229
12251230 /**
12261231 * <p>
1232 * Is {@code true} if this is Windows 8.
1233 * </p>
1234 * <p>
1235 * The field will return {@code false} if {@code OS_NAME} is {@code null}.
1236 * </p>
1237 *
1238 * @since 3.2
1239 */
1240 public static final boolean IS_OS_WINDOWS_8 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.2");
1241
1242 /**
1243 * <p>
12271244 * Gets the Java home directory as a {@code File}.
12281245 * </p>
12291246 *
12601277 * @param versionPrefix the prefix for the java version
12611278 * @return true if matches, or false if not or can't determine
12621279 */
1263 private static boolean getJavaVersionMatches(String versionPrefix) {
1280 private static boolean getJavaVersionMatches(final String versionPrefix) {
12641281 return isJavaVersionMatch(JAVA_SPECIFICATION_VERSION, versionPrefix);
12651282 }
12661283
12711288 * @param osVersionPrefix the prefix for the version
12721289 * @return true if matches, or false if not or can't determine
12731290 */
1274 private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) {
1291 private static boolean getOSMatches(final String osNamePrefix, final String osVersionPrefix) {
12751292 return isOSMatch(OS_NAME, OS_VERSION, osNamePrefix, osVersionPrefix);
12761293 }
12771294
12811298 * @param osNamePrefix the prefix for the os name
12821299 * @return true if matches, or false if not or can't determine
12831300 */
1284 private static boolean getOSMatchesName(String osNamePrefix) {
1301 private static boolean getOSMatchesName(final String osNamePrefix) {
12851302 return isOSNameMatch(OS_NAME, osNamePrefix);
12861303 }
12871304
12981315 * @param property the system property name
12991316 * @return the system property value or {@code null} if a security problem occurs
13001317 */
1301 private static String getSystemProperty(String property) {
1318 private static String getSystemProperty(final String property) {
13021319 try {
13031320 return System.getProperty(property);
1304 } catch (SecurityException ex) {
1321 } catch (final SecurityException ex) {
13051322 // we are not allowed to look at this property
13061323 System.err.println("Caught a SecurityException reading the system property '" + property
13071324 + "'; the SystemUtils property value will default to null.");
13661383 * @param requiredVersion the required version, for example 1.31f
13671384 * @return {@code true} if the actual version is equal or greater than the required version
13681385 */
1369 public static boolean isJavaVersionAtLeast(JavaVersion requiredVersion) {
1386 public static boolean isJavaVersionAtLeast(final JavaVersion requiredVersion) {
13701387 return JAVA_SPECIFICATION_VERSION_AS_ENUM.atLeast(requiredVersion);
13711388 }
13721389
13821399 * @param versionPrefix the prefix for the expected Java version
13831400 * @return true if matches, or false if not or can't determine
13841401 */
1385 static boolean isJavaVersionMatch(String version, String versionPrefix) {
1402 static boolean isJavaVersionMatch(final String version, final String versionPrefix) {
13861403 if (version == null) {
13871404 return false;
13881405 }
14011418 * @param osVersionPrefix the prefix for the expected OS version
14021419 * @return true if matches, or false if not or can't determine
14031420 */
1404 static boolean isOSMatch(String osName, String osVersion, String osNamePrefix, String osVersionPrefix) {
1421 static boolean isOSMatch(final String osName, final String osVersion, final String osNamePrefix, final String osVersionPrefix) {
14051422 if (osName == null || osVersion == null) {
14061423 return false;
14071424 }
14181435 * @param osNamePrefix the prefix for the expected OS name
14191436 * @return true if matches, or false if not or can't determine
14201437 */
1421 static boolean isOSNameMatch(String osName, String osNamePrefix) {
1438 static boolean isOSNameMatch(final String osName, final String osNamePrefix) {
14221439 if (osName == null) {
14231440 return false;
14241441 }
3030 * </ul>
3131 *
3232 * <p>All exceptions messages are
33 * <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax">format strings</a>
33 * <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax">format strings</a>
3434 * as defined by the Java platform. For example:</p>
3535 *
3636 * <pre>
3939 * </pre>
4040 *
4141 * <p>#ThreadSafe#</p>
42 * @version $Id: Validate.java 1199983 2011-11-09 21:41:24Z ggregory $
42 * @version $Id: Validate.java 1459653 2013-03-22 07:37:03Z bayard $
4343 * @see java.lang.String#format(String, Object...)
4444 * @since 2.0
4545 */
100100 * @see #isTrue(boolean, String, double)
101101 * @see #isTrue(boolean, String, Object...)
102102 */
103 public static void isTrue(boolean expression, String message, long value) {
103 public static void isTrue(final boolean expression, final String message, final long value) {
104104 if (expression == false) {
105105 throw new IllegalArgumentException(String.format(message, Long.valueOf(value)));
106106 }
125125 * @see #isTrue(boolean, String, long)
126126 * @see #isTrue(boolean, String, Object...)
127127 */
128 public static void isTrue(boolean expression, String message, double value) {
128 public static void isTrue(final boolean expression, final String message, final double value) {
129129 if (expression == false) {
130130 throw new IllegalArgumentException(String.format(message, Double.valueOf(value)));
131131 }
149149 * @see #isTrue(boolean, String, long)
150150 * @see #isTrue(boolean, String, double)
151151 */
152 public static void isTrue(boolean expression, String message, Object... values) {
152 public static void isTrue(final boolean expression, final String message, final Object... values) {
153153 if (expression == false) {
154154 throw new IllegalArgumentException(String.format(message, values));
155155 }
174174 * @see #isTrue(boolean, String, double)
175175 * @see #isTrue(boolean, String, Object...)
176176 */
177 public static void isTrue(boolean expression) {
177 public static void isTrue(final boolean expression) {
178178 if (expression == false) {
179179 throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE);
180180 }
198198 * @throws NullPointerException if the object is {@code null}
199199 * @see #notNull(Object, String, Object...)
200200 */
201 public static <T> T notNull(T object) {
201 public static <T> T notNull(final T object) {
202202 return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
203203 }
204204
216216 * @throws NullPointerException if the object is {@code null}
217217 * @see #notNull(Object)
218218 */
219 public static <T> T notNull(T object, String message, Object... values) {
219 public static <T> T notNull(final T object, final String message, final Object... values) {
220220 if (object == null) {
221221 throw new NullPointerException(String.format(message, values));
222222 }
242242 * @throws IllegalArgumentException if the array is empty
243243 * @see #notEmpty(Object[])
244244 */
245 public static <T> T[] notEmpty(T[] array, String message, Object... values) {
245 public static <T> T[] notEmpty(final T[] array, final String message, final Object... values) {
246246 if (array == null) {
247247 throw new NullPointerException(String.format(message, values));
248248 }
268268 * @throws IllegalArgumentException if the array is empty
269269 * @see #notEmpty(Object[], String, Object...)
270270 */
271 public static <T> T[] notEmpty(T[] array) {
271 public static <T> T[] notEmpty(final T[] array) {
272272 return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE);
273273 }
274274
291291 * @throws IllegalArgumentException if the collection is empty
292292 * @see #notEmpty(Object[])
293293 */
294 public static <T extends Collection<?>> T notEmpty(T collection, String message, Object... values) {
294 public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) {
295295 if (collection == null) {
296296 throw new NullPointerException(String.format(message, values));
297297 }
317317 * @throws IllegalArgumentException if the collection is empty
318318 * @see #notEmpty(Collection, String, Object...)
319319 */
320 public static <T extends Collection<?>> T notEmpty(T collection) {
320 public static <T extends Collection<?>> T notEmpty(final T collection) {
321321 return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE);
322322 }
323323
340340 * @throws IllegalArgumentException if the map is empty
341341 * @see #notEmpty(Object[])
342342 */
343 public static <T extends Map<?, ?>> T notEmpty(T map, String message, Object... values) {
343 public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) {
344344 if (map == null) {
345345 throw new NullPointerException(String.format(message, values));
346346 }
366366 * @throws IllegalArgumentException if the map is empty
367367 * @see #notEmpty(Map, String, Object...)
368368 */
369 public static <T extends Map<?, ?>> T notEmpty(T map) {
369 public static <T extends Map<?, ?>> T notEmpty(final T map) {
370370 return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE);
371371 }
372372
389389 * @throws IllegalArgumentException if the character sequence is empty
390390 * @see #notEmpty(CharSequence)
391391 */
392 public static <T extends CharSequence> T notEmpty(T chars, String message, Object... values) {
392 public static <T extends CharSequence> T notEmpty(final T chars, final String message, final Object... values) {
393393 if (chars == null) {
394394 throw new NullPointerException(String.format(message, values));
395395 }
416416 * @throws IllegalArgumentException if the character sequence is empty
417417 * @see #notEmpty(CharSequence, String, Object...)
418418 */
419 public static <T extends CharSequence> T notEmpty(T chars) {
419 public static <T extends CharSequence> T notEmpty(final T chars) {
420420 return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE);
421421 }
422422
442442 *
443443 * @since 3.0
444444 */
445 public static <T extends CharSequence> T notBlank(T chars, String message, Object... values) {
445 public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values) {
446446 if (chars == null) {
447447 throw new NullPointerException(String.format(message, values));
448448 }
471471 *
472472 * @since 3.0
473473 */
474 public static <T extends CharSequence> T notBlank(T chars) {
474 public static <T extends CharSequence> T notBlank(final T chars) {
475475 return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE);
476476 }
477477
501501 * @throws IllegalArgumentException if an element is {@code null}
502502 * @see #noNullElements(Object[])
503503 */
504 public static <T> T[] noNullElements(T[] array, String message, Object... values) {
504 public static <T> T[] noNullElements(final T[] array, final String message, final Object... values) {
505505 Validate.notNull(array);
506506 for (int i = 0; i < array.length; i++) {
507507 if (array[i] == null) {
508 Object[] values2 = ArrayUtils.add(values, Integer.valueOf(i));
508 final Object[] values2 = ArrayUtils.add(values, Integer.valueOf(i));
509509 throw new IllegalArgumentException(String.format(message, values2));
510510 }
511511 }
533533 * @throws IllegalArgumentException if an element is {@code null}
534534 * @see #noNullElements(Object[], String, Object...)
535535 */
536 public static <T> T[] noNullElements(T[] array) {
536 public static <T> T[] noNullElements(final T[] array) {
537537 return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE);
538538 }
539539
563563 * @throws IllegalArgumentException if an element is {@code null}
564564 * @see #noNullElements(Iterable)
565565 */
566 public static <T extends Iterable<?>> T noNullElements(T iterable, String message, Object... values) {
566 public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) {
567567 Validate.notNull(iterable);
568568 int i = 0;
569 for (Iterator<?> it = iterable.iterator(); it.hasNext(); i++) {
569 for (final Iterator<?> it = iterable.iterator(); it.hasNext(); i++) {
570570 if (it.next() == null) {
571 Object[] values2 = ArrayUtils.addAll(values, Integer.valueOf(i));
571 final Object[] values2 = ArrayUtils.addAll(values, Integer.valueOf(i));
572572 throw new IllegalArgumentException(String.format(message, values2));
573573 }
574574 }
596596 * @throws IllegalArgumentException if an element is {@code null}
597597 * @see #noNullElements(Iterable, String, Object...)
598598 */
599 public static <T extends Iterable<?>> T noNullElements(T iterable) {
599 public static <T extends Iterable<?>> T noNullElements(final T iterable) {
600600 return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE);
601601 }
602602
624624 *
625625 * @since 3.0
626626 */
627 public static <T> T[] validIndex(T[] array, int index, String message, Object... values) {
627 public static <T> T[] validIndex(final T[] array, final int index, final String message, final Object... values) {
628628 Validate.notNull(array);
629629 if (index < 0 || index >= array.length) {
630630 throw new IndexOutOfBoundsException(String.format(message, values));
655655 *
656656 * @since 3.0
657657 */
658 public static <T> T[] validIndex(T[] array, int index) {
658 public static <T> T[] validIndex(final T[] array, final int index) {
659659 return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index));
660660 }
661661
683683 *
684684 * @since 3.0
685685 */
686 public static <T extends Collection<?>> T validIndex(T collection, int index, String message, Object... values) {
686 public static <T extends Collection<?>> T validIndex(final T collection, final int index, final String message, final Object... values) {
687687 Validate.notNull(collection);
688688 if (index < 0 || index >= collection.size()) {
689689 throw new IndexOutOfBoundsException(String.format(message, values));
711711 *
712712 * @since 3.0
713713 */
714 public static <T extends Collection<?>> T validIndex(T collection, int index) {
714 public static <T extends Collection<?>> T validIndex(final T collection, final int index) {
715715 return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index));
716716 }
717717
740740 *
741741 * @since 3.0
742742 */
743 public static <T extends CharSequence> T validIndex(T chars, int index, String message, Object... values) {
743 public static <T extends CharSequence> T validIndex(final T chars, final int index, final String message, final Object... values) {
744744 Validate.notNull(chars);
745745 if (index < 0 || index >= chars.length()) {
746746 throw new IndexOutOfBoundsException(String.format(message, values));
772772 *
773773 * @since 3.0
774774 */
775 public static <T extends CharSequence> T validIndex(T chars, int index) {
775 public static <T extends CharSequence> T validIndex(final T chars, final int index) {
776776 return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index));
777777 }
778778
798798 *
799799 * @since 3.0
800800 */
801 public static void validState(boolean expression) {
801 public static void validState(final boolean expression) {
802802 if (expression == false) {
803803 throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE);
804804 }
820820 *
821821 * @since 3.0
822822 */
823 public static void validState(boolean expression, String message, Object... values) {
823 public static void validState(final boolean expression, final String message, final Object... values) {
824824 if (expression == false) {
825825 throw new IllegalStateException(String.format(message, values));
826826 }
844844 *
845845 * @since 3.0
846846 */
847 public static void matchesPattern(CharSequence input, String pattern) {
847 public static void matchesPattern(final CharSequence input, final String pattern) {
848 // TODO when breaking BC, consider returning input
848849 if (Pattern.matches(pattern, input) == false) {
849850 throw new IllegalArgumentException(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern));
850851 }
867868 *
868869 * @since 3.0
869870 */
870 public static void matchesPattern(CharSequence input, String pattern, String message, Object... values) {
871 public static void matchesPattern(final CharSequence input, final String pattern, final String message, final Object... values) {
872 // TODO when breaking BC, consider returning input
871873 if (Pattern.matches(pattern, input) == false) {
872874 throw new IllegalArgumentException(String.format(message, values));
873875 }
886888 * @param start the inclusive start value, not null
887889 * @param end the inclusive end value, not null
888890 * @param value the object to validate, not null
889 * @throws IllegalArgumentException if the value falls out of the boundaries
891 * @throws IllegalArgumentException if the value falls outside the boundaries
890892 * @see #inclusiveBetween(Object, Object, Comparable, String, Object...)
891893 *
892894 * @since 3.0
893895 */
894 public static <T> void inclusiveBetween(T start, T end, Comparable<T> value) {
896 public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value) {
897 // TODO when breaking BC, consider returning value
895898 if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
896899 throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
897900 }
910913 * @param value the object to validate, not null
911914 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
912915 * @param values the optional values for the formatted exception message, null array not recommended
913 * @throws IllegalArgumentException if the value falls out of the boundaries
916 * @throws IllegalArgumentException if the value falls outside the boundaries
914917 * @see #inclusiveBetween(Object, Object, Comparable)
915918 *
916919 * @since 3.0
917920 */
918 public static <T> void inclusiveBetween(T start, T end, Comparable<T> value, String message, Object... values) {
921 public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
922 // TODO when breaking BC, consider returning value
919923 if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
920924 throw new IllegalArgumentException(String.format(message, values));
921925 }
928932 * <p>Validate that the specified argument object fall between the two
929933 * exclusive values specified; otherwise, throws an exception.</p>
930934 *
931 * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
935 * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
932936 *
933937 * @param <T> the type of the argument object
934938 * @param start the exclusive start value, not null
935939 * @param end the exclusive end value, not null
936940 * @param value the object to validate, not null
937 * @throws IllegalArgumentException if the value falls out of the boundaries
941 * @throws IllegalArgumentException if the value falls outside the boundaries
938942 * @see #exclusiveBetween(Object, Object, Comparable, String, Object...)
939943 *
940944 * @since 3.0
941945 */
942 public static <T> void exclusiveBetween(T start, T end, Comparable<T> value) {
946 public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value) {
947 // TODO when breaking BC, consider returning value
943948 if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
944949 throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
945950 }
950955 * exclusive values specified; otherwise, throws an exception with the
951956 * specified message.</p>
952957 *
953 * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
958 * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
954959 *
955960 * @param <T> the type of the argument object
956961 * @param start the exclusive start value, not null
958963 * @param value the object to validate, not null
959964 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
960965 * @param values the optional values for the formatted exception message, null array not recommended
961 * @throws IllegalArgumentException if the value falls out of the boundaries
966 * @throws IllegalArgumentException if the value falls outside the boundaries
962967 * @see #exclusiveBetween(Object, Object, Comparable)
963968 *
964969 * @since 3.0
965970 */
966 public static <T> void exclusiveBetween(T start, T end, Comparable<T> value, String message, Object... values) {
971 public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
972 // TODO when breaking BC, consider returning value
967973 if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
968974 throw new IllegalArgumentException(String.format(message, values));
969975 }
988994 *
989995 * @since 3.0
990996 */
991 public static void isInstanceOf(Class<?> type, Object obj) {
997 public static void isInstanceOf(final Class<?> type, final Object obj) {
998 // TODO when breaking BC, consider returning obj
992999 if (type.isInstance(obj) == false) {
9931000 throw new IllegalArgumentException(String.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(),
9941001 obj == null ? "null" : obj.getClass().getName()));
10121019 *
10131020 * @since 3.0
10141021 */
1015 public static void isInstanceOf(Class<?> type, Object obj, String message, Object... values) {
1022 public static void isInstanceOf(final Class<?> type, final Object obj, final String message, final Object... values) {
1023 // TODO when breaking BC, consider returning obj
10161024 if (type.isInstance(obj) == false) {
10171025 throw new IllegalArgumentException(String.format(message, values));
10181026 }
10371045 *
10381046 * @since 3.0
10391047 */
1040 public static void isAssignableFrom(Class<?> superType, Class<?> type) {
1048 public static void isAssignableFrom(final Class<?> superType, final Class<?> type) {
1049 // TODO when breaking BC, consider returning type
10411050 if (superType.isAssignableFrom(type) == false) {
10421051 throw new IllegalArgumentException(String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, type == null ? "null" : type.getName(),
10431052 superType.getName()));
10611070 * @throws IllegalArgumentException if argument can not be converted to the specified class
10621071 * @see #isAssignableFrom(Class, Class)
10631072 */
1064 public static void isAssignableFrom(Class<?> superType, Class<?> type, String message, Object... values) {
1073 public static void isAssignableFrom(final Class<?> superType, final Class<?> type, final String message, final Object... values) {
1074 // TODO when breaking BC, consider returning type
10651075 if (superType.isAssignableFrom(type) == false) {
10661076 throw new IllegalArgumentException(String.format(message, values));
10671077 }
7474 * @param <T> the type of object that the builder will construct or compute.
7575 *
7676 * @since 3.0
77 * @version $Id: Builder.java 1088899 2011-04-05 05:31:27Z bayard $
77 * @version $Id: Builder.java 1455892 2013-03-13 11:35:00Z ggregory $
7878 */
7979 public interface Builder<T> {
8080
8484 *
8585 * @return the object constructed or result calculated by the builder.
8686 */
87 public T build();
87 T build();
8888 }
8282 * @see EqualsBuilder
8383 * @see HashCodeBuilder
8484 * @since 1.0
85 * @version $Id: CompareToBuilder.java 1199735 2011-11-09 13:11:07Z sebb $
85 * @version $Id: CompareToBuilder.java 1436770 2013-01-22 07:09:45Z ggregory $
8686 */
8787 public class CompareToBuilder implements Builder<Integer> {
8888
130130 * @throws ClassCastException if <code>rhs</code> is not assignment-compatible
131131 * with <code>lhs</code>
132132 */
133 public static int reflectionCompare(Object lhs, Object rhs) {
133 public static int reflectionCompare(final Object lhs, final Object rhs) {
134134 return reflectionCompare(lhs, rhs, false, null);
135135 }
136136
162162 * @throws ClassCastException if <code>rhs</code> is not assignment-compatible
163163 * with <code>lhs</code>
164164 */
165 public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients) {
165 public static int reflectionCompare(final Object lhs, final Object rhs, final boolean compareTransients) {
166166 return reflectionCompare(lhs, rhs, compareTransients, null);
167167 }
168168
195195 * with <code>lhs</code>
196196 * @since 2.2
197197 */
198 public static int reflectionCompare(Object lhs, Object rhs, Collection<String> excludeFields) {
198 public static int reflectionCompare(final Object lhs, final Object rhs, final Collection<String> excludeFields) {
199199 return reflectionCompare(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
200200 }
201201
228228 * with <code>lhs</code>
229229 * @since 2.2
230230 */
231 public static int reflectionCompare(Object lhs, Object rhs, String... excludeFields) {
231 public static int reflectionCompare(final Object lhs, final Object rhs, final String... excludeFields) {
232232 return reflectionCompare(lhs, rhs, false, null, excludeFields);
233233 }
234234
265265 * @since 2.2 (2.0 as <code>reflectionCompare(Object, Object, boolean, Class)</code>)
266266 */
267267 public static int reflectionCompare(
268 Object lhs,
269 Object rhs,
270 boolean compareTransients,
271 Class<?> reflectUpToClass,
272 String... excludeFields) {
268 final Object lhs,
269 final Object rhs,
270 final boolean compareTransients,
271 final Class<?> reflectUpToClass,
272 final String... excludeFields) {
273273
274274 if (lhs == rhs) {
275275 return 0;
281281 if (!lhsClazz.isInstance(rhs)) {
282282 throw new ClassCastException();
283283 }
284 CompareToBuilder compareToBuilder = new CompareToBuilder();
284 final CompareToBuilder compareToBuilder = new CompareToBuilder();
285285 reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields);
286286 while (lhsClazz.getSuperclass() != null && lhsClazz != reflectUpToClass) {
287287 lhsClazz = lhsClazz.getSuperclass();
302302 * @param excludeFields fields to exclude
303303 */
304304 private static void reflectionAppend(
305 Object lhs,
306 Object rhs,
307 Class<?> clazz,
308 CompareToBuilder builder,
309 boolean useTransients,
310 String[] excludeFields) {
305 final Object lhs,
306 final Object rhs,
307 final Class<?> clazz,
308 final CompareToBuilder builder,
309 final boolean useTransients,
310 final String[] excludeFields) {
311311
312 Field[] fields = clazz.getDeclaredFields();
312 final Field[] fields = clazz.getDeclaredFields();
313313 AccessibleObject.setAccessible(fields, true);
314314 for (int i = 0; i < fields.length && builder.comparison == 0; i++) {
315 Field f = fields[i];
315 final Field f = fields[i];
316316 if (!ArrayUtils.contains(excludeFields, f.getName())
317317 && (f.getName().indexOf('$') == -1)
318318 && (useTransients || !Modifier.isTransient(f.getModifiers()))
319319 && (!Modifier.isStatic(f.getModifiers()))) {
320320 try {
321321 builder.append(f.get(lhs), f.get(rhs));
322 } catch (IllegalAccessException e) {
322 } catch (final IllegalAccessException e) {
323323 // This can't happen. Would get a Security exception instead.
324324 // Throw a runtime exception in case the impossible happens.
325325 throw new InternalError("Unexpected IllegalAccessException");
337337 * @return this - used to chain append calls
338338 * @since 2.0
339339 */
340 public CompareToBuilder appendSuper(int superCompareTo) {
340 public CompareToBuilder appendSuper(final int superCompareTo) {
341341 if (comparison != 0) {
342342 return this;
343343 }
365365 * @throws ClassCastException if <code>rhs</code> is not assignment-compatible
366366 * with <code>lhs</code>
367367 */
368 public CompareToBuilder append(Object lhs, Object rhs) {
368 public CompareToBuilder append(final Object lhs, final Object rhs) {
369369 return append(lhs, rhs, null);
370370 }
371371
394394 * with <code>lhs</code>
395395 * @since 2.0
396396 */
397 public CompareToBuilder append(Object lhs, Object rhs, Comparator<?> comparator) {
397 public CompareToBuilder append(final Object lhs, final Object rhs, final Comparator<?> comparator) {
398398 if (comparison != 0) {
399399 return this;
400400 }
458458 * @param rhs right-hand value
459459 * @return this - used to chain append calls
460460 */
461 public CompareToBuilder append(long lhs, long rhs) {
461 public CompareToBuilder append(final long lhs, final long rhs) {
462462 if (comparison != 0) {
463463 return this;
464464 }
474474 * @param rhs right-hand value
475475 * @return this - used to chain append calls
476476 */
477 public CompareToBuilder append(int lhs, int rhs) {
477 public CompareToBuilder append(final int lhs, final int rhs) {
478478 if (comparison != 0) {
479479 return this;
480480 }
490490 * @param rhs right-hand value
491491 * @return this - used to chain append calls
492492 */
493 public CompareToBuilder append(short lhs, short rhs) {
493 public CompareToBuilder append(final short lhs, final short rhs) {
494494 if (comparison != 0) {
495495 return this;
496496 }
506506 * @param rhs right-hand value
507507 * @return this - used to chain append calls
508508 */
509 public CompareToBuilder append(char lhs, char rhs) {
509 public CompareToBuilder append(final char lhs, final char rhs) {
510510 if (comparison != 0) {
511511 return this;
512512 }
522522 * @param rhs right-hand value
523523 * @return this - used to chain append calls
524524 */
525 public CompareToBuilder append(byte lhs, byte rhs) {
525 public CompareToBuilder append(final byte lhs, final byte rhs) {
526526 if (comparison != 0) {
527527 return this;
528528 }
543543 * @param rhs right-hand value
544544 * @return this - used to chain append calls
545545 */
546 public CompareToBuilder append(double lhs, double rhs) {
546 public CompareToBuilder append(final double lhs, final double rhs) {
547547 if (comparison != 0) {
548548 return this;
549549 }
564564 * @param rhs right-hand value
565565 * @return this - used to chain append calls
566566 */
567 public CompareToBuilder append(float lhs, float rhs) {
567 public CompareToBuilder append(final float lhs, final float rhs) {
568568 if (comparison != 0) {
569569 return this;
570570 }
580580 * @param rhs right-hand value
581581 * @return this - used to chain append calls
582582 */
583 public CompareToBuilder append(boolean lhs, boolean rhs) {
583 public CompareToBuilder append(final boolean lhs, final boolean rhs) {
584584 if (comparison != 0) {
585585 return this;
586586 }
616616 * @throws ClassCastException if <code>rhs</code> is not assignment-compatible
617617 * with <code>lhs</code>
618618 */
619 public CompareToBuilder append(Object[] lhs, Object[] rhs) {
619 public CompareToBuilder append(final Object[] lhs, final Object[] rhs) {
620620 return append(lhs, rhs, null);
621621 }
622622
643643 * with <code>lhs</code>
644644 * @since 2.0
645645 */
646 public CompareToBuilder append(Object[] lhs, Object[] rhs, Comparator<?> comparator) {
646 public CompareToBuilder append(final Object[] lhs, final Object[] rhs, final Comparator<?> comparator) {
647647 if (comparison != 0) {
648648 return this;
649649 }
683683 * @param rhs right-hand array
684684 * @return this - used to chain append calls
685685 */
686 public CompareToBuilder append(long[] lhs, long[] rhs) {
686 public CompareToBuilder append(final long[] lhs, final long[] rhs) {
687687 if (comparison != 0) {
688688 return this;
689689 }
723723 * @param rhs right-hand array
724724 * @return this - used to chain append calls
725725 */
726 public CompareToBuilder append(int[] lhs, int[] rhs) {
726 public CompareToBuilder append(final int[] lhs, final int[] rhs) {
727727 if (comparison != 0) {
728728 return this;
729729 }
763763 * @param rhs right-hand array
764764 * @return this - used to chain append calls
765765 */
766 public CompareToBuilder append(short[] lhs, short[] rhs) {
766 public CompareToBuilder append(final short[] lhs, final short[] rhs) {
767767 if (comparison != 0) {
768768 return this;
769769 }
803803 * @param rhs right-hand array
804804 * @return this - used to chain append calls
805805 */
806 public CompareToBuilder append(char[] lhs, char[] rhs) {
806 public CompareToBuilder append(final char[] lhs, final char[] rhs) {
807807 if (comparison != 0) {
808808 return this;
809809 }
843843 * @param rhs right-hand array
844844 * @return this - used to chain append calls
845845 */
846 public CompareToBuilder append(byte[] lhs, byte[] rhs) {
846 public CompareToBuilder append(final byte[] lhs, final byte[] rhs) {
847847 if (comparison != 0) {
848848 return this;
849849 }
883883 * @param rhs right-hand array
884884 * @return this - used to chain append calls
885885 */
886 public CompareToBuilder append(double[] lhs, double[] rhs) {
886 public CompareToBuilder append(final double[] lhs, final double[] rhs) {
887887 if (comparison != 0) {
888888 return this;
889889 }
923923 * @param rhs right-hand array
924924 * @return this - used to chain append calls
925925 */
926 public CompareToBuilder append(float[] lhs, float[] rhs) {
926 public CompareToBuilder append(final float[] lhs, final float[] rhs) {
927927 if (comparison != 0) {
928928 return this;
929929 }
963963 * @param rhs right-hand array
964964 * @return this - used to chain append calls
965965 */
966 public CompareToBuilder append(boolean[] lhs, boolean[] rhs) {
966 public CompareToBuilder append(final boolean[] lhs, final boolean[] rhs) {
967967 if (comparison != 0) {
968968 return this;
969969 }
10121012 * @see #toComparison()
10131013 * @since 3.0
10141014 */
1015 @Override
10151016 public Integer build() {
10161017 return Integer.valueOf(toComparison());
10171018 }
3030 *
3131 * <p> This class provides methods to build a good equals method for any
3232 * class. It follows rules laid out in
33 * <a href="http://java.sun.com/docs/books/effective/index.html">Effective Java</a>
33 * <a href="http://www.oracle.com/technetwork/java/effectivejava-136174.html">Effective Java</a>
3434 * , by Joshua Bloch. In particular the rule for comparing <code>doubles</code>,
3535 * <code>floats</code>, and arrays can be tricky. Also, making sure that
3636 * <code>equals()</code> and <code>hashCode()</code> are consistent can be
7777 * </pre>
7878 *
7979 * @since 1.0
80 * @version $Id: EqualsBuilder.java 1091531 2011-04-12 18:29:49Z ggregory $
80 * @version $Id: EqualsBuilder.java 1535757 2013-10-25 15:07:13Z mbenson $
8181 */
8282 public class EqualsBuilder implements Builder<Boolean> {
8383
130130 *
131131 * @return the pair
132132 */
133 static Pair<IDKey, IDKey> getRegisterPair(Object lhs, Object rhs) {
134 IDKey left = new IDKey(lhs);
135 IDKey right = new IDKey(rhs);
133 static Pair<IDKey, IDKey> getRegisterPair(final Object lhs, final Object rhs) {
134 final IDKey left = new IDKey(lhs);
135 final IDKey right = new IDKey(rhs);
136136 return Pair.of(left, right);
137137 }
138138
149149 * @return boolean <code>true</code> if the registry contains the given object.
150150 * @since 3.0
151151 */
152 static boolean isRegistered(Object lhs, Object rhs) {
153 Set<Pair<IDKey, IDKey>> registry = getRegistry();
154 Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
155 Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getLeft(), pair.getRight());
152 static boolean isRegistered(final Object lhs, final Object rhs) {
153 final Set<Pair<IDKey, IDKey>> registry = getRegistry();
154 final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
155 final Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getLeft(), pair.getRight());
156156
157157 return registry != null
158158 && (registry.contains(pair) || registry.contains(swappedPair));
167167 * @param lhs <code>this</code> object to register
168168 * @param rhs the other object to register
169169 */
170 static void register(Object lhs, Object rhs) {
170 static void register(final Object lhs, final Object rhs) {
171171 synchronized (EqualsBuilder.class) {
172172 if (getRegistry() == null) {
173173 REGISTRY.set(new HashSet<Pair<IDKey, IDKey>>());
174174 }
175175 }
176176
177 Set<Pair<IDKey, IDKey>> registry = getRegistry();
178 Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
177 final Set<Pair<IDKey, IDKey>> registry = getRegistry();
178 final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
179179 registry.add(pair);
180180 }
181181
191191 * @param rhs the other object to unregister
192192 * @since 3.0
193193 */
194 static void unregister(Object lhs, Object rhs) {
194 static void unregister(final Object lhs, final Object rhs) {
195195 Set<Pair<IDKey, IDKey>> registry = getRegistry();
196196 if (registry != null) {
197 Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
197 final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
198198 registry.remove(pair);
199199 synchronized (EqualsBuilder.class) {
200200 //read again
243243 * @param excludeFields Collection of String field names to exclude from testing
244244 * @return <code>true</code> if the two Objects have tested equals.
245245 */
246 public static boolean reflectionEquals(Object lhs, Object rhs, Collection<String> excludeFields) {
246 public static boolean reflectionEquals(final Object lhs, final Object rhs, final Collection<String> excludeFields) {
247247 return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
248248 }
249249
266266 * @param excludeFields array of field names to exclude from testing
267267 * @return <code>true</code> if the two Objects have tested equals.
268268 */
269 public static boolean reflectionEquals(Object lhs, Object rhs, String... excludeFields) {
269 public static boolean reflectionEquals(final Object lhs, final Object rhs, final String... excludeFields) {
270270 return reflectionEquals(lhs, rhs, false, null, excludeFields);
271271 }
272272
290290 * @param testTransients whether to include transient fields
291291 * @return <code>true</code> if the two Objects have tested equals.
292292 */
293 public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) {
293 public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients) {
294294 return reflectionEquals(lhs, rhs, testTransients, null);
295295 }
296296
320320 * @return <code>true</code> if the two Objects have tested equals.
321321 * @since 2.0
322322 */
323 public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class<?> reflectUpToClass,
324 String... excludeFields) {
323 public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass,
324 final String... excludeFields) {
325325 if (lhs == rhs) {
326326 return true;
327327 }
332332 // class or in classes between the leaf and root.
333333 // If we are not testing transients or a subclass has no ivars,
334334 // then a subclass can test equals to a superclass.
335 Class<?> lhsClass = lhs.getClass();
336 Class<?> rhsClass = rhs.getClass();
335 final Class<?> lhsClass = lhs.getClass();
336 final Class<?> rhsClass = rhs.getClass();
337337 Class<?> testClass;
338338 if (lhsClass.isInstance(rhs)) {
339339 testClass = lhsClass;
351351 // The two classes are not related.
352352 return false;
353353 }
354 EqualsBuilder equalsBuilder = new EqualsBuilder();
354 final EqualsBuilder equalsBuilder = new EqualsBuilder();
355355 try {
356 reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
357 while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
358 testClass = testClass.getSuperclass();
356 if (testClass.isArray()) {
357 equalsBuilder.append(lhs, rhs);
358 } else {
359359 reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
360 while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
361 testClass = testClass.getSuperclass();
362 reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
363 }
360364 }
361 } catch (IllegalArgumentException e) {
365 } catch (final IllegalArgumentException e) {
362366 // In this case, we tried to test a subclass vs. a superclass and
363367 // the subclass has ivars or the ivars are transient and
364368 // we are testing transients.
381385 * @param excludeFields array of field names to exclude from testing
382386 */
383387 private static void reflectionAppend(
384 Object lhs,
385 Object rhs,
386 Class<?> clazz,
387 EqualsBuilder builder,
388 boolean useTransients,
389 String[] excludeFields) {
388 final Object lhs,
389 final Object rhs,
390 final Class<?> clazz,
391 final EqualsBuilder builder,
392 final boolean useTransients,
393 final String[] excludeFields) {
390394
391395 if (isRegistered(lhs, rhs)) {
392396 return;
394398
395399 try {
396400 register(lhs, rhs);
397 Field[] fields = clazz.getDeclaredFields();
401 final Field[] fields = clazz.getDeclaredFields();
398402 AccessibleObject.setAccessible(fields, true);
399403 for (int i = 0; i < fields.length && builder.isEquals; i++) {
400 Field f = fields[i];
404 final Field f = fields[i];
401405 if (!ArrayUtils.contains(excludeFields, f.getName())
402406 && (f.getName().indexOf('$') == -1)
403407 && (useTransients || !Modifier.isTransient(f.getModifiers()))
404408 && (!Modifier.isStatic(f.getModifiers()))) {
405409 try {
406410 builder.append(f.get(lhs), f.get(rhs));
407 } catch (IllegalAccessException e) {
411 } catch (final IllegalAccessException e) {
408412 //this can't happen. Would get a Security exception instead
409413 //throw a runtime exception in case the impossible happens.
410414 throw new InternalError("Unexpected IllegalAccessException");
425429 * @return EqualsBuilder - used to chain calls.
426430 * @since 2.0
427431 */
428 public EqualsBuilder appendSuper(boolean superEquals) {
432 public EqualsBuilder appendSuper(final boolean superEquals) {
429433 if (isEquals == false) {
430434 return this;
431435 }
443447 * @param rhs the right hand object
444448 * @return EqualsBuilder - used to chain calls.
445449 */
446 public EqualsBuilder append(Object lhs, Object rhs) {
447 if (isEquals == false) {
448 return this;
449 }
450 if (lhs == rhs) {
451 return this;
452 }
453 if (lhs == null || rhs == null) {
454 this.setEquals(false);
455 return this;
456 }
457 Class<?> lhsClass = lhs.getClass();
450 public EqualsBuilder append(final Object lhs, final Object rhs) {
451 if (isEquals == false) {
452 return this;
453 }
454 if (lhs == rhs) {
455 return this;
456 }
457 if (lhs == null || rhs == null) {
458 this.setEquals(false);
459 return this;
460 }
461 final Class<?> lhsClass = lhs.getClass();
458462 if (!lhsClass.isArray()) {
459463 // The simple case, not an array, just test the element
460464 isEquals = lhs.equals(rhs);
498502 * the right hand <code>long</code>
499503 * @return EqualsBuilder - used to chain calls.
500504 */
501 public EqualsBuilder append(long lhs, long rhs) {
505 public EqualsBuilder append(final long lhs, final long rhs) {
502506 if (isEquals == false) {
503507 return this;
504508 }
513517 * @param rhs the right hand <code>int</code>
514518 * @return EqualsBuilder - used to chain calls.
515519 */
516 public EqualsBuilder append(int lhs, int rhs) {
520 public EqualsBuilder append(final int lhs, final int rhs) {
517521 if (isEquals == false) {
518522 return this;
519523 }
528532 * @param rhs the right hand <code>short</code>
529533 * @return EqualsBuilder - used to chain calls.
530534 */
531 public EqualsBuilder append(short lhs, short rhs) {
535 public EqualsBuilder append(final short lhs, final short rhs) {
532536 if (isEquals == false) {
533537 return this;
534538 }
543547 * @param rhs the right hand <code>char</code>
544548 * @return EqualsBuilder - used to chain calls.
545549 */
546 public EqualsBuilder append(char lhs, char rhs) {
550 public EqualsBuilder append(final char lhs, final char rhs) {
547551 if (isEquals == false) {
548552 return this;
549553 }
558562 * @param rhs the right hand <code>byte</code>
559563 * @return EqualsBuilder - used to chain calls.
560564 */
561 public EqualsBuilder append(byte lhs, byte rhs) {
565 public EqualsBuilder append(final byte lhs, final byte rhs) {
562566 if (isEquals == false) {
563567 return this;
564568 }
579583 * @param rhs the right hand <code>double</code>
580584 * @return EqualsBuilder - used to chain calls.
581585 */
582 public EqualsBuilder append(double lhs, double rhs) {
586 public EqualsBuilder append(final double lhs, final double rhs) {
583587 if (isEquals == false) {
584588 return this;
585589 }
599603 * @param rhs the right hand <code>float</code>
600604 * @return EqualsBuilder - used to chain calls.
601605 */
602 public EqualsBuilder append(float lhs, float rhs) {
606 public EqualsBuilder append(final float lhs, final float rhs) {
603607 if (isEquals == false) {
604608 return this;
605609 }
613617 * @param rhs the right hand <code>boolean</code>
614618 * @return EqualsBuilder - used to chain calls.
615619 */
616 public EqualsBuilder append(boolean lhs, boolean rhs) {
620 public EqualsBuilder append(final boolean lhs, final boolean rhs) {
617621 if (isEquals == false) {
618622 return this;
619623 }
631635 * @param rhs the right hand <code>Object[]</code>
632636 * @return EqualsBuilder - used to chain calls.
633637 */
634 public EqualsBuilder append(Object[] lhs, Object[] rhs) {
638 public EqualsBuilder append(final Object[] lhs, final Object[] rhs) {
635639 if (isEquals == false) {
636640 return this;
637641 }
662666 * @param rhs the right hand <code>long[]</code>
663667 * @return EqualsBuilder - used to chain calls.
664668 */
665 public EqualsBuilder append(long[] lhs, long[] rhs) {
669 public EqualsBuilder append(final long[] lhs, final long[] rhs) {
666670 if (isEquals == false) {
667671 return this;
668672 }
693697 * @param rhs the right hand <code>int[]</code>
694698 * @return EqualsBuilder - used to chain calls.
695699 */
696 public EqualsBuilder append(int[] lhs, int[] rhs) {
700 public EqualsBuilder append(final int[] lhs, final int[] rhs) {
697701 if (isEquals == false) {
698702 return this;
699703 }
724728 * @param rhs the right hand <code>short[]</code>
725729 * @return EqualsBuilder - used to chain calls.
726730 */
727 public EqualsBuilder append(short[] lhs, short[] rhs) {
731 public EqualsBuilder append(final short[] lhs, final short[] rhs) {
728732 if (isEquals == false) {
729733 return this;
730734 }
755759 * @param rhs the right hand <code>char[]</code>
756760 * @return EqualsBuilder - used to chain calls.
757761 */
758 public EqualsBuilder append(char[] lhs, char[] rhs) {
762 public EqualsBuilder append(final char[] lhs, final char[] rhs) {
759763 if (isEquals == false) {
760764 return this;
761765 }
786790 * @param rhs the right hand <code>byte[]</code>
787791 * @return EqualsBuilder - used to chain calls.
788792 */
789 public EqualsBuilder append(byte[] lhs, byte[] rhs) {
793 public EqualsBuilder append(final byte[] lhs, final byte[] rhs) {
790794 if (isEquals == false) {
791795 return this;
792796 }
817821 * @param rhs the right hand <code>double[]</code>
818822 * @return EqualsBuilder - used to chain calls.
819823 */
820 public EqualsBuilder append(double[] lhs, double[] rhs) {
824 public EqualsBuilder append(final double[] lhs, final double[] rhs) {
821825 if (isEquals == false) {
822826 return this;
823827 }
848852 * @param rhs the right hand <code>float[]</code>
849853 * @return EqualsBuilder - used to chain calls.
850854 */
851 public EqualsBuilder append(float[] lhs, float[] rhs) {
855 public EqualsBuilder append(final float[] lhs, final float[] rhs) {
852856 if (isEquals == false) {
853857 return this;
854858 }
879883 * @param rhs the right hand <code>boolean[]</code>
880884 * @return EqualsBuilder - used to chain calls.
881885 */
882 public EqualsBuilder append(boolean[] lhs, boolean[] rhs) {
886 public EqualsBuilder append(final boolean[] lhs, final boolean[] rhs) {
883887 if (isEquals == false) {
884888 return this;
885889 }
919923 *
920924 * @since 3.0
921925 */
926 @Override
922927 public Boolean build() {
923928 return Boolean.valueOf(isEquals());
924929 }
929934 * @param isEquals The value to set.
930935 * @since 2.1
931936 */
932 protected void setEquals(boolean isEquals) {
937 protected void setEquals(final boolean isEquals) {
933938 this.isEquals = isEquals;
934939 }
935940
3232 *
3333 * <p>
3434 * This class enables a good <code>hashCode</code> method to be built for any class. It follows the rules laid out in
35 * the book <a href="http://java.sun.com/docs/books/effective/index.html">Effective Java</a> by Joshua Bloch. Writing a
35 * the book <a href="http://www.oracle.com/technetwork/java/effectivejava-136174.html">Effective Java</a> by Joshua Bloch. Writing a
3636 * good <code>hashCode</code> method is actually quite difficult. This class aims to simplify the process.
3737 * </p>
3838 *
9494 * </pre>
9595 *
9696 * @since 1.0
97 * @version $Id: HashCodeBuilder.java 1144929 2011-07-10 18:26:16Z ggregory $
97 * @version $Id: HashCodeBuilder.java 1526818 2013-09-27 07:53:53Z britter $
9898 */
9999 public class HashCodeBuilder implements Builder<Integer> {
100100 /**
146146 * @return boolean <code>true</code> if the registry contains the given object.
147147 * @since 2.3
148148 */
149 static boolean isRegistered(Object value) {
150 Set<IDKey> registry = getRegistry();
149 static boolean isRegistered(final Object value) {
150 final Set<IDKey> registry = getRegistry();
151151 return registry != null && registry.contains(new IDKey(value));
152152 }
153153
167167 * @param excludeFields
168168 * Collection of String field names to exclude from use in calculation of hash code
169169 */
170 private static void reflectionAppend(Object object, Class<?> clazz, HashCodeBuilder builder, boolean useTransients,
171 String[] excludeFields) {
170 private static void reflectionAppend(final Object object, final Class<?> clazz, final HashCodeBuilder builder, final boolean useTransients,
171 final String[] excludeFields) {
172172 if (isRegistered(object)) {
173173 return;
174174 }
175175 try {
176176 register(object);
177 Field[] fields = clazz.getDeclaredFields();
177 final Field[] fields = clazz.getDeclaredFields();
178178 AccessibleObject.setAccessible(fields, true);
179 for (Field field : fields) {
179 for (final Field field : fields) {
180180 if (!ArrayUtils.contains(excludeFields, field.getName())
181181 && (field.getName().indexOf('$') == -1)
182182 && (useTransients || !Modifier.isTransient(field.getModifiers()))
183183 && (!Modifier.isStatic(field.getModifiers()))) {
184184 try {
185 Object fieldValue = field.get(object);
185 final Object fieldValue = field.get(object);
186186 builder.append(fieldValue);
187 } catch (IllegalAccessException e) {
187 } catch (final IllegalAccessException e) {
188188 // this can't happen. Would get a Security exception instead
189189 // throw a runtime exception in case the impossible happens.
190190 throw new InternalError("Unexpected IllegalAccessException");
233233 * @throws IllegalArgumentException
234234 * if the number is zero or even
235235 */
236 public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object) {
236 public static int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final Object object) {
237237 return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, false, null);
238238 }
239239
276276 * @throws IllegalArgumentException
277277 * if the number is zero or even
278278 */
279 public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object,
280 boolean testTransients) {
279 public static int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final Object object,
280 final boolean testTransients) {
281281 return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, testTransients, null);
282282 }
283283
328328 * if the number is zero or even
329329 * @since 2.0
330330 */
331 public static <T> int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, T object,
332 boolean testTransients, Class<? super T> reflectUpToClass, String... excludeFields) {
331 public static <T> int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final T object,
332 final boolean testTransients, final Class<? super T> reflectUpToClass, final String... excludeFields) {
333333
334334 if (object == null) {
335335 throw new IllegalArgumentException("The object to build a hash code for must not be null");
336336 }
337 HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
337 final HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
338338 Class<?> clazz = object.getClass();
339339 reflectionAppend(object, clazz, builder, testTransients, excludeFields);
340340 while (clazz.getSuperclass() != null && clazz != reflectUpToClass) {
376376 * @throws IllegalArgumentException
377377 * if the object is <code>null</code>
378378 */
379 public static int reflectionHashCode(Object object, boolean testTransients) {
379 public static int reflectionHashCode(final Object object, final boolean testTransients) {
380380 return reflectionHashCode(17, 37, object, testTransients, null);
381381 }
382382
412412 * @throws IllegalArgumentException
413413 * if the object is <code>null</code>
414414 */
415 public static int reflectionHashCode(Object object, Collection<String> excludeFields) {
415 public static int reflectionHashCode(final Object object, final Collection<String> excludeFields) {
416416 return reflectionHashCode(object, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
417417 }
418418
450450 * @throws IllegalArgumentException
451451 * if the object is <code>null</code>
452452 */
453 public static int reflectionHashCode(Object object, String... excludeFields) {
453 public static int reflectionHashCode(final Object object, final String... excludeFields) {
454454 return reflectionHashCode(17, 37, object, false, null, excludeFields);
455455 }
456456
462462 * @param value
463463 * The object to register.
464464 */
465 static void register(Object value) {
465 static void register(final Object value) {
466466 synchronized (HashCodeBuilder.class) {
467467 if (getRegistry() == null) {
468468 REGISTRY.set(new HashSet<IDKey>());
483483 * The object to unregister.
484484 * @since 2.3
485485 */
486 static void unregister(Object value) {
486 static void unregister(final Object value) {
487487 Set<IDKey> registry = getRegistry();
488488 if (registry != null) {
489489 registry.remove(new IDKey(value));
519519
520520 /**
521521 * <p>
522 * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class,
522 * Two randomly chosen, odd numbers must be passed in. Ideally these should be different for each class,
523523 * however this is not vital.
524524 * </p>
525525 *
527527 * Prime numbers are preferred, especially for the multiplier.
528528 * </p>
529529 *
530 * @param initialNonZeroOddNumber
531 * a non-zero, odd number used as the initial value
532 * @param multiplierNonZeroOddNumber
533 * a non-zero, odd number used as the multiplier
530 * @param initialOddNumber
531 * an odd number used as the initial value
532 * @param multiplierOddNumber
533 * an odd number used as the multiplier
534534 * @throws IllegalArgumentException
535 * if the number is zero or even
536 */
537 public HashCodeBuilder(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) {
538 if (initialNonZeroOddNumber == 0) {
539 throw new IllegalArgumentException("HashCodeBuilder requires a non zero initial value");
540 }
541 if (initialNonZeroOddNumber % 2 == 0) {
535 * if the number is even
536 */
537 public HashCodeBuilder(final int initialOddNumber, final int multiplierOddNumber) {
538 if (initialOddNumber % 2 == 0) {
542539 throw new IllegalArgumentException("HashCodeBuilder requires an odd initial value");
543540 }
544 if (multiplierNonZeroOddNumber == 0) {
545 throw new IllegalArgumentException("HashCodeBuilder requires a non zero multiplier");
546 }
547 if (multiplierNonZeroOddNumber % 2 == 0) {
541 if (multiplierOddNumber % 2 == 0) {
548542 throw new IllegalArgumentException("HashCodeBuilder requires an odd multiplier");
549543 }
550 iConstant = multiplierNonZeroOddNumber;
551 iTotal = initialNonZeroOddNumber;
544 iConstant = multiplierOddNumber;
545 iTotal = initialOddNumber;
552546 }
553547
554548 /**
572566 * the boolean to add to the <code>hashCode</code>
573567 * @return this
574568 */
575 public HashCodeBuilder append(boolean value) {
569 public HashCodeBuilder append(final boolean value) {
576570 iTotal = iTotal * iConstant + (value ? 0 : 1);
577571 return this;
578572 }
586580 * the array to add to the <code>hashCode</code>
587581 * @return this
588582 */
589 public HashCodeBuilder append(boolean[] array) {
583 public HashCodeBuilder append(final boolean[] array) {
590584 if (array == null) {
591585 iTotal = iTotal * iConstant;
592586 } else {
593 for (boolean element : array) {
587 for (final boolean element : array) {
594588 append(element);
595589 }
596590 }
608602 * the byte to add to the <code>hashCode</code>
609603 * @return this
610604 */
611 public HashCodeBuilder append(byte value) {
605 public HashCodeBuilder append(final byte value) {
612606 iTotal = iTotal * iConstant + value;
613607 return this;
614608 }
624618 * the array to add to the <code>hashCode</code>
625619 * @return this
626620 */
627 public HashCodeBuilder append(byte[] array) {
621 public HashCodeBuilder append(final byte[] array) {
628622 if (array == null) {
629623 iTotal = iTotal * iConstant;
630624 } else {
631 for (byte element : array) {
625 for (final byte element : array) {
632626 append(element);
633627 }
634628 }
644638 * the char to add to the <code>hashCode</code>
645639 * @return this
646640 */
647 public HashCodeBuilder append(char value) {
641 public HashCodeBuilder append(final char value) {
648642 iTotal = iTotal * iConstant + value;
649643 return this;
650644 }
658652 * the array to add to the <code>hashCode</code>
659653 * @return this
660654 */
661 public HashCodeBuilder append(char[] array) {
655 public HashCodeBuilder append(final char[] array) {
662656 if (array == null) {
663657 iTotal = iTotal * iConstant;
664658 } else {
665 for (char element : array) {
659 for (final char element : array) {
666660 append(element);
667661 }
668662 }
678672 * the double to add to the <code>hashCode</code>
679673 * @return this
680674 */
681 public HashCodeBuilder append(double value) {
675 public HashCodeBuilder append(final double value) {
682676 return append(Double.doubleToLongBits(value));
683677 }
684678
691685 * the array to add to the <code>hashCode</code>
692686 * @return this
693687 */
694 public HashCodeBuilder append(double[] array) {
688 public HashCodeBuilder append(final double[] array) {
695689 if (array == null) {
696690 iTotal = iTotal * iConstant;
697691 } else {
698 for (double element : array) {
692 for (final double element : array) {
699693 append(element);
700694 }
701695 }
711705 * the float to add to the <code>hashCode</code>
712706 * @return this
713707 */
714 public HashCodeBuilder append(float value) {
708 public HashCodeBuilder append(final float value) {
715709 iTotal = iTotal * iConstant + Float.floatToIntBits(value);
716710 return this;
717711 }
725719 * the array to add to the <code>hashCode</code>
726720 * @return this
727721 */
728 public HashCodeBuilder append(float[] array) {
722 public HashCodeBuilder append(final float[] array) {
729723 if (array == null) {
730724 iTotal = iTotal * iConstant;
731725 } else {
732 for (float element : array) {
726 for (final float element : array) {
733727 append(element);
734728 }
735729 }
745739 * the int to add to the <code>hashCode</code>
746740 * @return this
747741 */
748 public HashCodeBuilder append(int value) {
742 public HashCodeBuilder append(final int value) {
749743 iTotal = iTotal * iConstant + value;
750744 return this;
751745 }
759753 * the array to add to the <code>hashCode</code>
760754 * @return this
761755 */
762 public HashCodeBuilder append(int[] array) {
756 public HashCodeBuilder append(final int[] array) {
763757 if (array == null) {
764758 iTotal = iTotal * iConstant;
765759 } else {
766 for (int element : array) {
760 for (final int element : array) {
767761 append(element);
768762 }
769763 }
783777 // Long.hashCode do. Ideally we should switch to >>> at
784778 // some stage. There are backwards compat issues, so
785779 // that will have to wait for the time being. cf LANG-342.
786 public HashCodeBuilder append(long value) {
780 public HashCodeBuilder append(final long value) {
787781 iTotal = iTotal * iConstant + ((int) (value ^ (value >> 32)));
788782 return this;
789783 }
797791 * the array to add to the <code>hashCode</code>
798792 * @return this
799793 */
800 public HashCodeBuilder append(long[] array) {
794 public HashCodeBuilder append(final long[] array) {
801795 if (array == null) {
802796 iTotal = iTotal * iConstant;
803797 } else {
804 for (long element : array) {
798 for (final long element : array) {
805799 append(element);
806800 }
807801 }
817811 * the Object to add to the <code>hashCode</code>
818812 * @return this
819813 */
820 public HashCodeBuilder append(Object object) {
814 public HashCodeBuilder append(final Object object) {
821815 if (object == null) {
822816 iTotal = iTotal * iConstant;
823817
861855 * the array to add to the <code>hashCode</code>
862856 * @return this
863857 */
864 public HashCodeBuilder append(Object[] array) {
858 public HashCodeBuilder append(final Object[] array) {
865859 if (array == null) {
866860 iTotal = iTotal * iConstant;
867861 } else {
868 for (Object element : array) {
862 for (final Object element : array) {
869863 append(element);
870864 }
871865 }
881875 * the short to add to the <code>hashCode</code>
882876 * @return this
883877 */
884 public HashCodeBuilder append(short value) {
878 public HashCodeBuilder append(final short value) {
885879 iTotal = iTotal * iConstant + value;
886880 return this;
887881 }
895889 * the array to add to the <code>hashCode</code>
896890 * @return this
897891 */
898 public HashCodeBuilder append(short[] array) {
892 public HashCodeBuilder append(final short[] array) {
899893 if (array == null) {
900894 iTotal = iTotal * iConstant;
901895 } else {
902 for (short element : array) {
896 for (final short element : array) {
903897 append(element);
904898 }
905899 }
916910 * @return this HashCodeBuilder, used to chain calls.
917911 * @since 2.0
918912 */
919 public HashCodeBuilder appendSuper(int superHashCode) {
913 public HashCodeBuilder appendSuper(final int superHashCode) {
920914 iTotal = iTotal * iConstant + superHashCode;
921915 return this;
922916 }
939933 *
940934 * @since 3.0
941935 */
936 @Override
942937 public Integer build() {
943938 return Integer.valueOf(toHashCode());
944939 }
3535 * Constructor for IDKey
3636 * @param _value The value
3737 */
38 public IDKey(Object _value) {
38 public IDKey(final Object _value) {
3939 // This is the Object hashcode
4040 id = System.identityHashCode(_value);
4141 // There have been some cases (LANG-459) that return the
5959 * @return if the instances are for the same object
6060 */
6161 @Override
62 public boolean equals(Object other) {
62 public boolean equals(final Object other) {
6363 if (!(other instanceof IDKey)) {
6464 return false;
6565 }
66 IDKey idKey = (IDKey) other;
66 final IDKey idKey = (IDKey) other;
6767 if (id != idKey.id) {
6868 return false;
6969 }
8282 * </p>
8383 *
8484 * @since 2.0
85 * @version $Id: ReflectionToStringBuilder.java 1200177 2011-11-10 06:14:33Z ggregory $
85 * @version $Id: ReflectionToStringBuilder.java 1448370 2013-02-20 19:54:19Z tn $
8686 */
8787 public class ReflectionToStringBuilder extends ToStringBuilder {
8888
108108 * @throws IllegalArgumentException
109109 * if the Object is <code>null</code>
110110 */
111 public static String toString(Object object) {
111 public static String toString(final Object object) {
112112 return toString(object, null, false, false, null);
113113 }
114114
140140 * @throws IllegalArgumentException
141141 * if the Object or <code>ToStringStyle</code> is <code>null</code>
142142 */
143 public static String toString(Object object, ToStringStyle style) {
143 public static String toString(final Object object, final ToStringStyle style) {
144144 return toString(object, style, false, false, null);
145145 }
146146
178178 * @throws IllegalArgumentException
179179 * if the Object is <code>null</code>
180180 */
181 public static String toString(Object object, ToStringStyle style, boolean outputTransients) {
181 public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) {
182182 return toString(object, style, outputTransients, false, null);
183183 }
184184
224224 * if the Object is <code>null</code>
225225 * @since 2.1
226226 */
227 public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) {
227 public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) {
228228 return toString(object, style, outputTransients, outputStatics, null);
229229 }
230230
276276 * @since 2.1
277277 */
278278 public static <T> String toString(
279 T object, ToStringStyle style, boolean outputTransients,
280 boolean outputStatics, Class<? super T> reflectUpToClass) {
279 final T object, final ToStringStyle style, final boolean outputTransients,
280 final boolean outputStatics, final Class<? super T> reflectUpToClass) {
281281 return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics)
282282 .toString();
283283 }
291291 * The field names to exclude. Null excludes nothing.
292292 * @return The toString value.
293293 */
294 public static String toStringExclude(Object object, Collection<String> excludeFieldNames) {
294 public static String toStringExclude(final Object object, final Collection<String> excludeFieldNames) {
295295 return toStringExclude(object, toNoNullStringArray(excludeFieldNames));
296296 }
297297
304304 * The collection to convert
305305 * @return A new array of Strings.
306306 */
307 static String[] toNoNullStringArray(Collection<String> collection) {
307 static String[] toNoNullStringArray(final Collection<String> collection) {
308308 if (collection == null) {
309309 return ArrayUtils.EMPTY_STRING_ARRAY;
310310 }
320320 * The array to check
321321 * @return The given array or a new array without null.
322322 */
323 static String[] toNoNullStringArray(Object[] array) {
324 List<String> list = new ArrayList<String>(array.length);
325 for (Object e : array) {
323 static String[] toNoNullStringArray(final Object[] array) {
324 final List<String> list = new ArrayList<String>(array.length);
325 for (final Object e : array) {
326326 if (e != null) {
327327 list.add(e.toString());
328328 }
340340 * The field names to exclude
341341 * @return The toString value.
342342 */
343 public static String toStringExclude(Object object, String... excludeFieldNames) {
343 public static String toStringExclude(final Object object, final String... excludeFieldNames) {
344344 return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString();
345345 }
346346
380380 * @throws IllegalArgumentException
381381 * if the Object passed in is <code>null</code>
382382 */
383 public ReflectionToStringBuilder(Object object) {
383 public ReflectionToStringBuilder(final Object object) {
384384 super(object);
385385 }
386386
400400 * @throws IllegalArgumentException
401401 * if the Object passed in is <code>null</code>
402402 */
403 public ReflectionToStringBuilder(Object object, ToStringStyle style) {
403 public ReflectionToStringBuilder(final Object object, final ToStringStyle style) {
404404 super(object, style);
405405 }
406406
426426 * @throws IllegalArgumentException
427427 * if the Object passed in is <code>null</code>
428428 */
429 public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
429 public ReflectionToStringBuilder(final Object object, final ToStringStyle style, final StringBuffer buffer) {
430430 super(object, style, buffer);
431431 }
432432
450450 * @since 2.1
451451 */
452452 public <T> ReflectionToStringBuilder(
453 T object, ToStringStyle style, StringBuffer buffer,
454 Class<? super T> reflectUpToClass, boolean outputTransients, boolean outputStatics) {
453 final T object, final ToStringStyle style, final StringBuffer buffer,
454 final Class<? super T> reflectUpToClass, final boolean outputTransients, final boolean outputStatics) {
455455 super(object, style, buffer);
456456 this.setUpToClass(reflectUpToClass);
457457 this.setAppendTransients(outputTransients);
463463 * <ul>
464464 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
465465 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
466 * <li>Inner class fields are not appened.</li>
466 * <li>Inner class fields are not appended.</li>
467467 * </ul>
468468 *
469469 * @param field
470470 * The Field to test.
471471 * @return Whether or not to append the given <code>Field</code>.
472472 */
473 protected boolean accept(Field field) {
473 protected boolean accept(final Field field) {
474474 if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
475475 // Reject field from inner class.
476476 return false;
504504 * @param clazz
505505 * The class of object parameter
506506 */
507 protected void appendFieldsIn(Class<?> clazz) {
507 protected void appendFieldsIn(final Class<?> clazz) {
508508 if (clazz.isArray()) {
509509 this.reflectionAppendArray(this.getObject());
510510 return;
511511 }
512 Field[] fields = clazz.getDeclaredFields();
512 final Field[] fields = clazz.getDeclaredFields();
513513 AccessibleObject.setAccessible(fields, true);
514 for (Field field : fields) {
515 String fieldName = field.getName();
514 for (final Field field : fields) {
515 final String fieldName = field.getName();
516516 if (this.accept(field)) {
517517 try {
518518 // Warning: Field.get(Object) creates wrappers objects
519519 // for primitive types.
520 Object fieldValue = this.getValue(field);
520 final Object fieldValue = this.getValue(field);
521521 this.append(fieldName, fieldValue);
522 } catch (IllegalAccessException ex) {
522 } catch (final IllegalAccessException ex) {
523523 //this can't happen. Would get a Security exception
524524 // instead
525525 //throw a runtime exception in case the impossible
564564 *
565565 * @see java.lang.reflect.Field#get(Object)
566566 */
567 protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {
567 protected Object getValue(final Field field) throws IllegalArgumentException, IllegalAccessException {
568568 return field.get(this.getObject());
569569 }
570570
600600 * the array to add to the <code>toString</code>
601601 * @return this
602602 */
603 public ReflectionToStringBuilder reflectionAppendArray(Object array) {
603 public ReflectionToStringBuilder reflectionAppendArray(final Object array) {
604604 this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array);
605605 return this;
606606 }
614614 * Whether or not to append static fields.
615615 * @since 2.1
616616 */
617 public void setAppendStatics(boolean appendStatics) {
617 public void setAppendStatics(final boolean appendStatics) {
618618 this.appendStatics = appendStatics;
619619 }
620620
626626 * @param appendTransients
627627 * Whether or not to append transient fields.
628628 */
629 public void setAppendTransients(boolean appendTransients) {
629 public void setAppendTransients(final boolean appendTransients) {
630630 this.appendTransients = appendTransients;
631631 }
632632
637637 * The excludeFieldNames to excluding from toString or <code>null</code>.
638638 * @return <code>this</code>
639639 */
640 public ReflectionToStringBuilder setExcludeFieldNames(String... excludeFieldNamesParam) {
640 public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) {
641641 if (excludeFieldNamesParam == null) {
642642 this.excludeFieldNames = null;
643643 } else {
656656 * @param clazz
657657 * The last super class to stop appending fields for.
658658 */
659 public void setUpToClass(Class<?> clazz) {
659 public void setUpToClass(final Class<?> clazz) {
660660 if (clazz != null) {
661 Object object = getObject();
661 final Object object = getObject();
662662 if (object != null && clazz.isInstance(object) == false) {
663663 throw new IllegalArgumentException("Specified class is not a superclass of the object");
664664 }
2525 * program to access.</p>
2626 *
2727 * @since 1.0
28 * @version $Id: StandardToStringStyle.java 1089740 2011-04-07 05:01:54Z bayard $
28 * @version $Id: StandardToStringStyle.java 1436768 2013-01-22 07:07:42Z ggregory $
2929 */
3030 public class StandardToStringStyle extends ToStringStyle {
3131
6161 * @param useClassName the new useClassName flag
6262 */
6363 @Override
64 public void setUseClassName(boolean useClassName) { // NOPMD as this is implementing the abstract class
64 public void setUseClassName(final boolean useClassName) { // NOPMD as this is implementing the abstract class
6565 super.setUseClassName(useClassName);
6666 }
6767
8585 * @since 2.0
8686 */
8787 @Override
88 public void setUseShortClassName(boolean useShortClassName) { // NOPMD as this is implementing the abstract class
88 public void setUseShortClassName(final boolean useShortClassName) { // NOPMD as this is implementing the abstract class
8989 super.setUseShortClassName(useShortClassName);
9090 }
9191
106106 * @param useIdentityHashCode the new useIdentityHashCode flag
107107 */
108108 @Override
109 public void setUseIdentityHashCode(boolean useIdentityHashCode) { // NOPMD as this is implementing the abstract class
109 public void setUseIdentityHashCode(final boolean useIdentityHashCode) { // NOPMD as this is implementing the abstract class
110110 super.setUseIdentityHashCode(useIdentityHashCode);
111111 }
112112
128128 * @param useFieldNames the new useFieldNames flag
129129 */
130130 @Override
131 public void setUseFieldNames(boolean useFieldNames) { // NOPMD as this is implementing the abstract class
131 public void setUseFieldNames(final boolean useFieldNames) { // NOPMD as this is implementing the abstract class
132132 super.setUseFieldNames(useFieldNames);
133133 }
134134
152152 * @param defaultFullDetail the new defaultFullDetail flag
153153 */
154154 @Override
155 public void setDefaultFullDetail(boolean defaultFullDetail) { // NOPMD as this is implementing the abstract class
155 public void setDefaultFullDetail(final boolean defaultFullDetail) { // NOPMD as this is implementing the abstract class
156156 super.setDefaultFullDetail(defaultFullDetail);
157157 }
158158
174174 * @param arrayContentDetail the new arrayContentDetail flag
175175 */
176176 @Override
177 public void setArrayContentDetail(boolean arrayContentDetail) { // NOPMD as this is implementing the abstract class
177 public void setArrayContentDetail(final boolean arrayContentDetail) { // NOPMD as this is implementing the abstract class
178178 super.setArrayContentDetail(arrayContentDetail);
179179 }
180180
199199 * @param arrayStart the new array start text
200200 */
201201 @Override
202 public void setArrayStart(String arrayStart) { // NOPMD as this is implementing the abstract class
202 public void setArrayStart(final String arrayStart) { // NOPMD as this is implementing the abstract class
203203 super.setArrayStart(arrayStart);
204204 }
205205
224224 * @param arrayEnd the new array end text
225225 */
226226 @Override
227 public void setArrayEnd(String arrayEnd) { // NOPMD as this is implementing the abstract class
227 public void setArrayEnd(final String arrayEnd) { // NOPMD as this is implementing the abstract class
228228 super.setArrayEnd(arrayEnd);
229229 }
230230
249249 * @param arraySeparator the new array separator text
250250 */
251251 @Override
252 public void setArraySeparator(String arraySeparator) { // NOPMD as this is implementing the abstract class
252 public void setArraySeparator(final String arraySeparator) { // NOPMD as this is implementing the abstract class
253253 super.setArraySeparator(arraySeparator);
254254 }
255255
274274 * @param contentStart the new content start text
275275 */
276276 @Override
277 public void setContentStart(String contentStart) { // NOPMD as this is implementing the abstract class
277 public void setContentStart(final String contentStart) { // NOPMD as this is implementing the abstract class
278278 super.setContentStart(contentStart);
279279 }
280280
299299 * @param contentEnd the new content end text
300300 */
301301 @Override
302 public void setContentEnd(String contentEnd) { // NOPMD as this is implementing the abstract class
302 public void setContentEnd(final String contentEnd) { // NOPMD as this is implementing the abstract class
303303 super.setContentEnd(contentEnd);
304304 }
305305
324324 * @param fieldNameValueSeparator the new field name value separator text
325325 */
326326 @Override
327 public void setFieldNameValueSeparator(String fieldNameValueSeparator) { // NOPMD as this is implementing the abstract class
327 public void setFieldNameValueSeparator(final String fieldNameValueSeparator) { // NOPMD as this is implementing the abstract class
328328 super.setFieldNameValueSeparator(fieldNameValueSeparator);
329329 }
330330
349349 * @param fieldSeparator the new field separator text
350350 */
351351 @Override
352 public void setFieldSeparator(String fieldSeparator) { // NOPMD as this is implementing the abstract class
352 public void setFieldSeparator(final String fieldSeparator) { // NOPMD as this is implementing the abstract class
353353 super.setFieldSeparator(fieldSeparator);
354354 }
355355
375375 * @since 2.0
376376 */
377377 @Override
378 public void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) { // NOPMD as this is implementing the abstract class
378 public void setFieldSeparatorAtStart(final boolean fieldSeparatorAtStart) { // NOPMD as this is implementing the abstract class
379379 super.setFieldSeparatorAtStart(fieldSeparatorAtStart);
380380 }
381381
401401 * @since 2.0
402402 */
403403 @Override
404 public void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) { // NOPMD as this is implementing the abstract class
404 public void setFieldSeparatorAtEnd(final boolean fieldSeparatorAtEnd) { // NOPMD as this is implementing the abstract class
405405 super.setFieldSeparatorAtEnd(fieldSeparatorAtEnd);
406406 }
407407
426426 * @param nullText the new text to output when <code>null</code> found
427427 */
428428 @Override
429 public void setNullText(String nullText) { // NOPMD as this is implementing the abstract class
429 public void setNullText(final String nullText) { // NOPMD as this is implementing the abstract class
430430 super.setNullText(nullText);
431431 }
432432
457457 * @param sizeStartText the new start of size text
458458 */
459459 @Override
460 public void setSizeStartText(String sizeStartText) { // NOPMD as this is implementing the abstract class
460 public void setSizeStartText(final String sizeStartText) { // NOPMD as this is implementing the abstract class
461461 super.setSizeStartText(sizeStartText);
462462 }
463463
488488 * @param sizeEndText the new end of size text
489489 */
490490 @Override
491 public void setSizeEndText(String sizeEndText) { // NOPMD as this is implementing the abstract class
491 public void setSizeEndText(final String sizeEndText) { // NOPMD as this is implementing the abstract class
492492 super.setSizeEndText(sizeEndText);
493493 }
494494
519519 * @param summaryObjectStartText the new start of summary text
520520 */
521521 @Override
522 public void setSummaryObjectStartText(String summaryObjectStartText) { // NOPMD as this is implementing the abstract class
522 public void setSummaryObjectStartText(final String summaryObjectStartText) { // NOPMD as this is implementing the abstract class
523523 super.setSummaryObjectStartText(summaryObjectStartText);
524524 }
525525
550550 * @param summaryObjectEndText the new end of summary text
551551 */
552552 @Override
553 public void setSummaryObjectEndText(String summaryObjectEndText) { // NOPMD as this is implementing the abstract class
553 public void setSummaryObjectEndText(final String summaryObjectEndText) { // NOPMD as this is implementing the abstract class
554554 super.setSummaryObjectEndText(summaryObjectEndText);
555555 }
556556
8383 * the {@link ToStringStyle} passed into the constructor.</p>
8484 *
8585 * @since 1.0
86 * @version $Id: ToStringBuilder.java 1088899 2011-04-05 05:31:27Z bayard $
86 * @version $Id: ToStringBuilder.java 1533551 2013-10-18 16:49:15Z sebb $
8787 */
8888 public class ToStringBuilder implements Builder<String> {
8989
131131 * @param style the default <code>ToStringStyle</code>
132132 * @throws IllegalArgumentException if the style is <code>null</code>
133133 */
134 public static void setDefaultStyle(ToStringStyle style) {
134 public static void setDefaultStyle(final ToStringStyle style) {
135135 if (style == null) {
136136 throw new IllegalArgumentException("The style must not be null");
137137 }
147147 * @return the String result
148148 * @see ReflectionToStringBuilder#toString(Object)
149149 */
150 public static String reflectionToString(Object object) {
150 public static String reflectionToString(final Object object) {
151151 return ReflectionToStringBuilder.toString(object);
152152 }
153153
160160 * @return the String result
161161 * @see ReflectionToStringBuilder#toString(Object,ToStringStyle)
162162 */
163 public static String reflectionToString(Object object, ToStringStyle style) {
163 public static String reflectionToString(final Object object, final ToStringStyle style) {
164164 return ReflectionToStringBuilder.toString(object, style);
165165 }
166166
174174 * @return the String result
175175 * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean)
176176 */
177 public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) {
177 public static String reflectionToString(final Object object, final ToStringStyle style, final boolean outputTransients) {
178178 return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null);
179179 }
180180
192192 * @since 2.0
193193 */
194194 public static <T> String reflectionToString(
195 T object,
196 ToStringStyle style,
197 boolean outputTransients,
198 Class<? super T> reflectUpToClass) {
195 final T object,
196 final ToStringStyle style,
197 final boolean outputTransients,
198 final Class<? super T> reflectUpToClass) {
199199 return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass);
200200 }
201201
221221 *
222222 * @param object the Object to build a <code>toString</code> for, not recommended to be null
223223 */
224 public ToStringBuilder(Object object) {
224 public ToStringBuilder(final Object object) {
225225 this(object, null, null);
226226 }
227227
233233 * @param object the Object to build a <code>toString</code> for, not recommended to be null
234234 * @param style the style of the <code>toString</code> to create, null uses the default style
235235 */
236 public ToStringBuilder(Object object, ToStringStyle style) {
236 public ToStringBuilder(final Object object, final ToStringStyle style) {
237237 this(object, style, null);
238238 }
239239
248248 * @param style the style of the <code>toString</code> to create, null uses the default style
249249 * @param buffer the <code>StringBuffer</code> to populate, may be null
250250 */
251 public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
251 public ToStringBuilder(final Object object, ToStringStyle style, StringBuffer buffer) {
252252 if (style == null) {
253253 style = getDefaultStyle();
254254 }
271271 * @param value the value to add to the <code>toString</code>
272272 * @return this
273273 */
274 public ToStringBuilder append(boolean value) {
274 public ToStringBuilder append(final boolean value) {
275275 style.append(buffer, null, value);
276276 return this;
277277 }
285285 * @param array the array to add to the <code>toString</code>
286286 * @return this
287287 */
288 public ToStringBuilder append(boolean[] array) {
288 public ToStringBuilder append(final boolean[] array) {
289289 style.append(buffer, null, array, null);
290290 return this;
291291 }
299299 * @param value the value to add to the <code>toString</code>
300300 * @return this
301301 */
302 public ToStringBuilder append(byte value) {
302 public ToStringBuilder append(final byte value) {
303303 style.append(buffer, null, value);
304304 return this;
305305 }
313313 * @param array the array to add to the <code>toString</code>
314314 * @return this
315315 */
316 public ToStringBuilder append(byte[] array) {
316 public ToStringBuilder append(final byte[] array) {
317317 style.append(buffer, null, array, null);
318318 return this;
319319 }
327327 * @param value the value to add to the <code>toString</code>
328328 * @return this
329329 */
330 public ToStringBuilder append(char value) {
330 public ToStringBuilder append(final char value) {
331331 style.append(buffer, null, value);
332332 return this;
333333 }
341341 * @param array the array to add to the <code>toString</code>
342342 * @return this
343343 */
344 public ToStringBuilder append(char[] array) {
344 public ToStringBuilder append(final char[] array) {
345345 style.append(buffer, null, array, null);
346346 return this;
347347 }
355355 * @param value the value to add to the <code>toString</code>
356356 * @return this
357357 */
358 public ToStringBuilder append(double value) {
358 public ToStringBuilder append(final double value) {
359359 style.append(buffer, null, value);
360360 return this;
361361 }
369369 * @param array the array to add to the <code>toString</code>
370370 * @return this
371371 */
372 public ToStringBuilder append(double[] array) {
372 public ToStringBuilder append(final double[] array) {
373373 style.append(buffer, null, array, null);
374374 return this;
375375 }
383383 * @param value the value to add to the <code>toString</code>
384384 * @return this
385385 */
386 public ToStringBuilder append(float value) {
386 public ToStringBuilder append(final float value) {
387387 style.append(buffer, null, value);
388388 return this;
389389 }
397397 * @param array the array to add to the <code>toString</code>
398398 * @return this
399399 */
400 public ToStringBuilder append(float[] array) {
400 public ToStringBuilder append(final float[] array) {
401401 style.append(buffer, null, array, null);
402402 return this;
403403 }
411411 * @param value the value to add to the <code>toString</code>
412412 * @return this
413413 */
414 public ToStringBuilder append(int value) {
414 public ToStringBuilder append(final int value) {
415415 style.append(buffer, null, value);
416416 return this;
417417 }
425425 * @param array the array to add to the <code>toString</code>
426426 * @return this
427427 */
428 public ToStringBuilder append(int[] array) {
428 public ToStringBuilder append(final int[] array) {
429429 style.append(buffer, null, array, null);
430430 return this;
431431 }
439439 * @param value the value to add to the <code>toString</code>
440440 * @return this
441441 */
442 public ToStringBuilder append(long value) {
442 public ToStringBuilder append(final long value) {
443443 style.append(buffer, null, value);
444444 return this;
445445 }
453453 * @param array the array to add to the <code>toString</code>
454454 * @return this
455455 */
456 public ToStringBuilder append(long[] array) {
456 public ToStringBuilder append(final long[] array) {
457457 style.append(buffer, null, array, null);
458458 return this;
459459 }
467467 * @param obj the value to add to the <code>toString</code>
468468 * @return this
469469 */
470 public ToStringBuilder append(Object obj) {
470 public ToStringBuilder append(final Object obj) {
471471 style.append(buffer, null, obj, null);
472472 return this;
473473 }
481481 * @param array the array to add to the <code>toString</code>
482482 * @return this
483483 */
484 public ToStringBuilder append(Object[] array) {
484 public ToStringBuilder append(final Object[] array) {
485485 style.append(buffer, null, array, null);
486486 return this;
487487 }
495495 * @param value the value to add to the <code>toString</code>
496496 * @return this
497497 */
498 public ToStringBuilder append(short value) {
498 public ToStringBuilder append(final short value) {
499499 style.append(buffer, null, value);
500500 return this;
501501 }
509509 * @param array the array to add to the <code>toString</code>
510510 * @return this
511511 */
512 public ToStringBuilder append(short[] array) {
512 public ToStringBuilder append(final short[] array) {
513513 style.append(buffer, null, array, null);
514514 return this;
515515 }
522522 * @param value the value to add to the <code>toString</code>
523523 * @return this
524524 */
525 public ToStringBuilder append(String fieldName, boolean value) {
525 public ToStringBuilder append(final String fieldName, final boolean value) {
526526 style.append(buffer, fieldName, value);
527527 return this;
528528 }
535535 * @param array the array to add to the <code>hashCode</code>
536536 * @return this
537537 */
538 public ToStringBuilder append(String fieldName, boolean[] array) {
538 public ToStringBuilder append(final String fieldName, final boolean[] array) {
539539 style.append(buffer, fieldName, array, null);
540540 return this;
541541 }
555555 * for summary info
556556 * @return this
557557 */
558 public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) {
558 public ToStringBuilder append(final String fieldName, final boolean[] array, final boolean fullDetail) {
559559 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
560560 return this;
561561 }
568568 * @param value the value to add to the <code>toString</code>
569569 * @return this
570570 */
571 public ToStringBuilder append(String fieldName, byte value) {
571 public ToStringBuilder append(final String fieldName, final byte value) {
572572 style.append(buffer, fieldName, value);
573573 return this;
574574 }
580580 * @param array the array to add to the <code>toString</code>
581581 * @return this
582582 */
583 public ToStringBuilder append(String fieldName, byte[] array) {
583 public ToStringBuilder append(final String fieldName, final byte[] array) {
584584 style.append(buffer, fieldName, array, null);
585585 return this;
586586 }
600600 * for summary info
601601 * @return this
602602 */
603 public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) {
603 public ToStringBuilder append(final String fieldName, final byte[] array, final boolean fullDetail) {
604604 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
605605 return this;
606606 }
613613 * @param value the value to add to the <code>toString</code>
614614 * @return this
615615 */
616 public ToStringBuilder append(String fieldName, char value) {
616 public ToStringBuilder append(final String fieldName, final char value) {
617617 style.append(buffer, fieldName, value);
618618 return this;
619619 }
626626 * @param array the array to add to the <code>toString</code>
627627 * @return this
628628 */
629 public ToStringBuilder append(String fieldName, char[] array) {
629 public ToStringBuilder append(final String fieldName, final char[] array) {
630630 style.append(buffer, fieldName, array, null);
631631 return this;
632632 }
646646 * for summary info
647647 * @return this
648648 */
649 public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) {
649 public ToStringBuilder append(final String fieldName, final char[] array, final boolean fullDetail) {
650650 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
651651 return this;
652652 }
659659 * @param value the value to add to the <code>toString</code>
660660 * @return this
661661 */
662 public ToStringBuilder append(String fieldName, double value) {
662 public ToStringBuilder append(final String fieldName, final double value) {
663663 style.append(buffer, fieldName, value);
664664 return this;
665665 }
672672 * @param array the array to add to the <code>toString</code>
673673 * @return this
674674 */
675 public ToStringBuilder append(String fieldName, double[] array) {
675 public ToStringBuilder append(final String fieldName, final double[] array) {
676676 style.append(buffer, fieldName, array, null);
677677 return this;
678678 }
692692 * for summary info
693693 * @return this
694694 */
695 public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) {
695 public ToStringBuilder append(final String fieldName, final double[] array, final boolean fullDetail) {
696696 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
697697 return this;
698698 }
705705 * @param value the value to add to the <code>toString</code>
706706 * @return this
707707 */
708 public ToStringBuilder append(String fieldName, float value) {
708 public ToStringBuilder append(final String fieldName, final float value) {
709709 style.append(buffer, fieldName, value);
710710 return this;
711711 }
718718 * @param array the array to add to the <code>toString</code>
719719 * @return this
720720 */
721 public ToStringBuilder append(String fieldName, float[] array) {
721 public ToStringBuilder append(final String fieldName, final float[] array) {
722722 style.append(buffer, fieldName, array, null);
723723 return this;
724724 }
738738 * for summary info
739739 * @return this
740740 */
741 public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) {
741 public ToStringBuilder append(final String fieldName, final float[] array, final boolean fullDetail) {
742742 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
743743 return this;
744744 }
751751 * @param value the value to add to the <code>toString</code>
752752 * @return this
753753 */
754 public ToStringBuilder append(String fieldName, int value) {
754 public ToStringBuilder append(final String fieldName, final int value) {
755755 style.append(buffer, fieldName, value);
756756 return this;
757757 }
764764 * @param array the array to add to the <code>toString</code>
765765 * @return this
766766 */
767 public ToStringBuilder append(String fieldName, int[] array) {
767 public ToStringBuilder append(final String fieldName, final int[] array) {
768768 style.append(buffer, fieldName, array, null);
769769 return this;
770770 }
784784 * for summary info
785785 * @return this
786786 */
787 public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) {
787 public ToStringBuilder append(final String fieldName, final int[] array, final boolean fullDetail) {
788788 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
789789 return this;
790790 }
797797 * @param value the value to add to the <code>toString</code>
798798 * @return this
799799 */
800 public ToStringBuilder append(String fieldName, long value) {
800 public ToStringBuilder append(final String fieldName, final long value) {
801801 style.append(buffer, fieldName, value);
802802 return this;
803803 }
810810 * @param array the array to add to the <code>toString</code>
811811 * @return this
812812 */
813 public ToStringBuilder append(String fieldName, long[] array) {
813 public ToStringBuilder append(final String fieldName, final long[] array) {
814814 style.append(buffer, fieldName, array, null);
815815 return this;
816816 }
830830 * for summary info
831831 * @return this
832832 */
833 public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) {
833 public ToStringBuilder append(final String fieldName, final long[] array, final boolean fullDetail) {
834834 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
835835 return this;
836836 }
843843 * @param obj the value to add to the <code>toString</code>
844844 * @return this
845845 */
846 public ToStringBuilder append(String fieldName, Object obj) {
846 public ToStringBuilder append(final String fieldName, final Object obj) {
847847 style.append(buffer, fieldName, obj, null);
848848 return this;
849849 }
858858 * <code>false</code> for summary info
859859 * @return this
860860 */
861 public ToStringBuilder append(String fieldName, Object obj, boolean fullDetail) {
861 public ToStringBuilder append(final String fieldName, final Object obj, final boolean fullDetail) {
862862 style.append(buffer, fieldName, obj, Boolean.valueOf(fullDetail));
863863 return this;
864864 }
871871 * @param array the array to add to the <code>toString</code>
872872 * @return this
873873 */
874 public ToStringBuilder append(String fieldName, Object[] array) {
874 public ToStringBuilder append(final String fieldName, final Object[] array) {
875875 style.append(buffer, fieldName, array, null);
876876 return this;
877877 }
891891 * for summary info
892892 * @return this
893893 */
894 public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) {
894 public ToStringBuilder append(final String fieldName, final Object[] array, final boolean fullDetail) {
895895 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
896896 return this;
897897 }
904904 * @param value the value to add to the <code>toString</code>
905905 * @return this
906906 */
907 public ToStringBuilder append(String fieldName, short value) {
907 public ToStringBuilder append(final String fieldName, final short value) {
908908 style.append(buffer, fieldName, value);
909909 return this;
910910 }
917917 * @param array the array to add to the <code>toString</code>
918918 * @return this
919919 */
920 public ToStringBuilder append(String fieldName, short[] array) {
920 public ToStringBuilder append(final String fieldName, final short[] array) {
921921 style.append(buffer, fieldName, array, null);
922922 return this;
923923 }
937937 * for summary info
938938 * @return this
939939 */
940 public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) {
940 public ToStringBuilder append(final String fieldName, final short[] array, final boolean fullDetail) {
941941 style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
942942 return this;
943943 }
947947 * </code> method. Appends the class name followed by
948948 * {@link System#identityHashCode(java.lang.Object)}.</p>
949949 *
950 * @param object the <code>Object</code> whose class name and id to output
950 * @param srcObject the <code>Object</code> whose class name and id to output
951951 * @return this
952952 * @since 2.0
953953 */
954 public ToStringBuilder appendAsObjectToString(Object object) {
955 ObjectUtils.identityToString(this.getStringBuffer(), object);
954 public ToStringBuilder appendAsObjectToString(final Object srcObject) {
955 ObjectUtils.identityToString(this.getStringBuffer(), srcObject);
956956 return this;
957957 }
958958
970970 * @return this
971971 * @since 2.0
972972 */
973 public ToStringBuilder appendSuper(String superToString) {
973 public ToStringBuilder appendSuper(final String superToString) {
974974 if (superToString != null) {
975975 style.appendSuper(buffer, superToString);
976976 }
10041004 * @return this
10051005 * @since 2.0
10061006 */
1007 public ToStringBuilder appendToString(String toString) {
1007 public ToStringBuilder appendToString(final String toString) {
10081008 if (toString != null) {
10091009 style.appendToString(buffer, toString);
10101010 }
10721072 *
10731073 * @since 3.0
10741074 */
1075 @Override
10751076 public String build() {
10761077 return toString();
10771078 }
6060 * </p>
6161 *
6262 * @since 1.0
63 * @version $Id: ToStringStyle.java 1091066 2011-04-11 13:30:11Z mbenson $
63 * @version $Id: ToStringStyle.java 1525014 2013-09-20 14:08:12Z britter $
6464 */
6565 public abstract class ToStringStyle implements Serializable {
6666
8080 public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();
8181
8282 /**
83 * The multi line toString style. Using the Using the <code>Person</code>
83 * The multi line toString style. Using the <code>Person</code>
8484 * example from {@link ToStringBuilder}, the output would look like this:
8585 *
8686 * <pre>
134134 */
135135 private static final ThreadLocal<WeakHashMap<Object, Object>> REGISTRY =
136136 new ThreadLocal<WeakHashMap<Object,Object>>();
137 /*
138 * Note that objects of this class are generally shared between threads, so
139 * an instance variable would not be suitable here.
140 *
141 * In normal use the registry should always be left empty, because the caller
142 * should call toString() which will clean up.
143 *
144 * See LANG-792
145 */
137146
138147 /**
139148 * <p>
158167 * @return boolean <code>true</code> if the registry contains the given
159168 * object.
160169 */
161 static boolean isRegistered(Object value) {
162 Map<Object, Object> m = getRegistry();
170 static boolean isRegistered(final Object value) {
171 final Map<Object, Object> m = getRegistry();
163172 return m != null && m.containsKey(value);
164173 }
165174
172181 * @param value
173182 * The object to register.
174183 */
175 static void register(Object value) {
184 static void register(final Object value) {
176185 if (value != null) {
177 Map<Object, Object> m = getRegistry();
186 final Map<Object, Object> m = getRegistry();
178187 if (m == null) {
179188 REGISTRY.set(new WeakHashMap<Object, Object>());
180189 }
194203 * @param value
195204 * The object to unregister.
196205 */
197 static void unregister(Object value) {
206 static void unregister(final Object value) {
198207 if (value != null) {
199 Map<Object, Object> m = getRegistry();
208 final Map<Object, Object> m = getRegistry();
200209 if (m != null) {
201210 m.remove(value);
202211 if (m.isEmpty()) {
328337 * @param superToString the <code>super.toString()</code>
329338 * @since 2.0
330339 */
331 public void appendSuper(StringBuffer buffer, String superToString) {
340 public void appendSuper(final StringBuffer buffer, final String superToString) {
332341 appendToString(buffer, superToString);
333342 }
334343
342351 * @param toString the additional <code>toString</code>
343352 * @since 2.0
344353 */
345 public void appendToString(StringBuffer buffer, String toString) {
354 public void appendToString(final StringBuffer buffer, final String toString) {
346355 if (toString != null) {
347 int pos1 = toString.indexOf(contentStart) + contentStart.length();
348 int pos2 = toString.lastIndexOf(contentEnd);
356 final int pos1 = toString.indexOf(contentStart) + contentStart.length();
357 final int pos2 = toString.lastIndexOf(contentEnd);
349358 if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {
350 String data = toString.substring(pos1, pos2);
359 final String data = toString.substring(pos1, pos2);
351360 if (fieldSeparatorAtStart) {
352361 removeLastFieldSeparator(buffer);
353362 }
363372 * @param buffer the <code>StringBuffer</code> to populate
364373 * @param object the <code>Object</code> to build a <code>toString</code> for
365374 */
366 public void appendStart(StringBuffer buffer, Object object) {
375 public void appendStart(final StringBuffer buffer, final Object object) {
367376 if (object != null) {
368377 appendClassName(buffer, object);
369378 appendIdentityHashCode(buffer, object);
381390 * @param object the <code>Object</code> to build a
382391 * <code>toString</code> for.
383392 */
384 public void appendEnd(StringBuffer buffer, Object object) {
393 public void appendEnd(final StringBuffer buffer, final Object object) {
385394 if (this.fieldSeparatorAtEnd == false) {
386395 removeLastFieldSeparator(buffer);
387396 }
395404 * @param buffer the <code>StringBuffer</code> to populate
396405 * @since 2.0
397406 */
398 protected void removeLastFieldSeparator(StringBuffer buffer) {
399 int len = buffer.length();
400 int sepLen = fieldSeparator.length();
407 protected void removeLastFieldSeparator(final StringBuffer buffer) {
408 final int len = buffer.length();
409 final int sepLen = fieldSeparator.length();
401410 if (len > 0 && sepLen > 0 && len >= sepLen) {
402411 boolean match = true;
403412 for (int i = 0; i < sepLen; i++) {
425434 * @param fullDetail <code>true</code> for detail, <code>false</code>
426435 * for summary info, <code>null</code> for style decides
427436 */
428 public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
437 public void append(final StringBuffer buffer, final String fieldName, final Object value, final Boolean fullDetail) {
429438 appendFieldStart(buffer, fieldName);
430439
431440 if (value == null) {
457466 * not <code>null</code>
458467 * @param detail output detail or not
459468 */
460 protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {
469 protected void appendInternal(final StringBuffer buffer, final String fieldName, final Object value, final boolean detail) {
461470 if (isRegistered(value)
462471 && !(value instanceof Number || value instanceof Boolean || value instanceof Character)) {
463472 appendCyclicObject(buffer, fieldName, value);
568577 *
569578 * @since 2.2
570579 */
571 protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {
580 protected void appendCyclicObject(final StringBuffer buffer, final String fieldName, final Object value) {
572581 ObjectUtils.identityToString(buffer, value);
573582 }
574583
581590 * @param value the value to add to the <code>toString</code>,
582591 * not <code>null</code>
583592 */
584 protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
593 protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) {
585594 buffer.append(value);
586595 }
587596
593602 * @param coll the <code>Collection</code> to add to the
594603 * <code>toString</code>, not <code>null</code>
595604 */
596 protected void appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll) {
605 protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) {
597606 buffer.append(coll);
598607 }
599608
605614 * @param map the <code>Map</code> to add to the <code>toString</code>,
606615 * not <code>null</code>
607616 */
608 protected void appendDetail(StringBuffer buffer, String fieldName, Map<?, ?> map) {
617 protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map<?, ?> map) {
609618 buffer.append(map);
610619 }
611620
618627 * @param value the value to add to the <code>toString</code>,
619628 * not <code>null</code>
620629 */
621 protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {
630 protected void appendSummary(final StringBuffer buffer, final String fieldName, final Object value) {
622631 buffer.append(summaryObjectStartText);
623632 buffer.append(getShortClassName(value.getClass()));
624633 buffer.append(summaryObjectEndText);
634643 * @param fieldName the field name
635644 * @param value the value to add to the <code>toString</code>
636645 */
637 public void append(StringBuffer buffer, String fieldName, long value) {
646 public void append(final StringBuffer buffer, final String fieldName, final long value) {
638647 appendFieldStart(buffer, fieldName);
639648 appendDetail(buffer, fieldName, value);
640649 appendFieldEnd(buffer, fieldName);
648657 * @param fieldName the field name, typically not used as already appended
649658 * @param value the value to add to the <code>toString</code>
650659 */
651 protected void appendDetail(StringBuffer buffer, String fieldName, long value) {
660 protected void appendDetail(final StringBuffer buffer, final String fieldName, final long value) {
652661 buffer.append(value);
653662 }
654663
662671 * @param fieldName the field name
663672 * @param value the value to add to the <code>toString</code>
664673 */
665 public void append(StringBuffer buffer, String fieldName, int value) {
674 public void append(final StringBuffer buffer, final String fieldName, final int value) {
666675 appendFieldStart(buffer, fieldName);
667676 appendDetail(buffer, fieldName, value);
668677 appendFieldEnd(buffer, fieldName);
676685 * @param fieldName the field name, typically not used as already appended
677686 * @param value the value to add to the <code>toString</code>
678687 */
679 protected void appendDetail(StringBuffer buffer, String fieldName, int value) {
688 protected void appendDetail(final StringBuffer buffer, final String fieldName, final int value) {
680689 buffer.append(value);
681690 }
682691
690699 * @param fieldName the field name
691700 * @param value the value to add to the <code>toString</code>
692701 */
693 public void append(StringBuffer buffer, String fieldName, short value) {
702 public void append(final StringBuffer buffer, final String fieldName, final short value) {
694703 appendFieldStart(buffer, fieldName);
695704 appendDetail(buffer, fieldName, value);
696705 appendFieldEnd(buffer, fieldName);
704713 * @param fieldName the field name, typically not used as already appended
705714 * @param value the value to add to the <code>toString</code>
706715 */
707 protected void appendDetail(StringBuffer buffer, String fieldName, short value) {
716 protected void appendDetail(final StringBuffer buffer, final String fieldName, final short value) {
708717 buffer.append(value);
709718 }
710719
718727 * @param fieldName the field name
719728 * @param value the value to add to the <code>toString</code>
720729 */
721 public void append(StringBuffer buffer, String fieldName, byte value) {
730 public void append(final StringBuffer buffer, final String fieldName, final byte value) {
722731 appendFieldStart(buffer, fieldName);
723732 appendDetail(buffer, fieldName, value);
724733 appendFieldEnd(buffer, fieldName);
732741 * @param fieldName the field name, typically not used as already appended
733742 * @param value the value to add to the <code>toString</code>
734743 */
735 protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {
744 protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte value) {
736745 buffer.append(value);
737746 }
738747
746755 * @param fieldName the field name
747756 * @param value the value to add to the <code>toString</code>
748757 */
749 public void append(StringBuffer buffer, String fieldName, char value) {
758 public void append(final StringBuffer buffer, final String fieldName, final char value) {
750759 appendFieldStart(buffer, fieldName);
751760 appendDetail(buffer, fieldName, value);
752761 appendFieldEnd(buffer, fieldName);
760769 * @param fieldName the field name, typically not used as already appended
761770 * @param value the value to add to the <code>toString</code>
762771 */
763 protected void appendDetail(StringBuffer buffer, String fieldName, char value) {
772 protected void appendDetail(final StringBuffer buffer, final String fieldName, final char value) {
764773 buffer.append(value);
765774 }
766775
774783 * @param fieldName the field name
775784 * @param value the value to add to the <code>toString</code>
776785 */
777 public void append(StringBuffer buffer, String fieldName, double value) {
786 public void append(final StringBuffer buffer, final String fieldName, final double value) {
778787 appendFieldStart(buffer, fieldName);
779788 appendDetail(buffer, fieldName, value);
780789 appendFieldEnd(buffer, fieldName);
788797 * @param fieldName the field name, typically not used as already appended
789798 * @param value the value to add to the <code>toString</code>
790799 */
791 protected void appendDetail(StringBuffer buffer, String fieldName, double value) {
800 protected void appendDetail(final StringBuffer buffer, final String fieldName, final double value) {
792801 buffer.append(value);
793802 }
794803
802811 * @param fieldName the field name
803812 * @param value the value to add to the <code>toString</code>
804813 */
805 public void append(StringBuffer buffer, String fieldName, float value) {
814 public void append(final StringBuffer buffer, final String fieldName, final float value) {
806815 appendFieldStart(buffer, fieldName);
807816 appendDetail(buffer, fieldName, value);
808817 appendFieldEnd(buffer, fieldName);
816825 * @param fieldName the field name, typically not used as already appended
817826 * @param value the value to add to the <code>toString</code>
818827 */
819 protected void appendDetail(StringBuffer buffer, String fieldName, float value) {
828 protected void appendDetail(final StringBuffer buffer, final String fieldName, final float value) {
820829 buffer.append(value);
821830 }
822831
830839 * @param fieldName the field name
831840 * @param value the value to add to the <code>toString</code>
832841 */
833 public void append(StringBuffer buffer, String fieldName, boolean value) {
842 public void append(final StringBuffer buffer, final String fieldName, final boolean value) {
834843 appendFieldStart(buffer, fieldName);
835844 appendDetail(buffer, fieldName, value);
836845 appendFieldEnd(buffer, fieldName);
844853 * @param fieldName the field name, typically not used as already appended
845854 * @param value the value to add to the <code>toString</code>
846855 */
847 protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {
856 protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean value) {
848857 buffer.append(value);
849858 }
850859
858867 * @param fullDetail <code>true</code> for detail, <code>false</code>
859868 * for summary info, <code>null</code> for style decides
860869 */
861 public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {
870 public void append(final StringBuffer buffer, final String fieldName, final Object[] array, final Boolean fullDetail) {
862871 appendFieldStart(buffer, fieldName);
863872
864873 if (array == null) {
885894 * @param array the array to add to the <code>toString</code>,
886895 * not <code>null</code>
887896 */
888 protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {
897 protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object[] array) {
889898 buffer.append(arrayStart);
890899 for (int i = 0; i < array.length; i++) {
891 Object item = array[i];
900 final Object item = array[i];
892901 if (i > 0) {
893902 buffer.append(arraySeparator);
894903 }
911920 * not <code>null</code>
912921 * @since 2.0
913922 */
914 protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {
923 protected void reflectionAppendArrayDetail(final StringBuffer buffer, final String fieldName, final Object array) {
915924 buffer.append(arrayStart);
916 int length = Array.getLength(array);
925 final int length = Array.getLength(array);
917926 for (int i = 0; i < length; i++) {
918 Object item = Array.get(array, i);
927 final Object item = Array.get(array, i);
919928 if (i > 0) {
920929 buffer.append(arraySeparator);
921930 }
938947 * @param array the array to add to the <code>toString</code>,
939948 * not <code>null</code>
940949 */
941 protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {
950 protected void appendSummary(final StringBuffer buffer, final String fieldName, final Object[] array) {
942951 appendSummarySize(buffer, fieldName, array.length);
943952 }
944953
954963 * @param fullDetail <code>true</code> for detail, <code>false</code>
955964 * for summary info, <code>null</code> for style decides
956965 */
957 public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {
966 public void append(final StringBuffer buffer, final String fieldName, final long[] array, final Boolean fullDetail) {
958967 appendFieldStart(buffer, fieldName);
959968
960969 if (array == null) {
979988 * @param array the array to add to the <code>toString</code>,
980989 * not <code>null</code>
981990 */
982 protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {
991 protected void appendDetail(final StringBuffer buffer, final String fieldName, final long[] array) {
983992 buffer.append(arrayStart);
984993 for (int i = 0; i < array.length; i++) {
985994 if (i > 0) {
9991008 * @param array the array to add to the <code>toString</code>,
10001009 * not <code>null</code>
10011010 */
1002 protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {
1011 protected void appendSummary(final StringBuffer buffer, final String fieldName, final long[] array) {
10031012 appendSummarySize(buffer, fieldName, array.length);
10041013 }
10051014
10151024 * @param fullDetail <code>true</code> for detail, <code>false</code>
10161025 * for summary info, <code>null</code> for style decides
10171026 */
1018 public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {
1027 public void append(final StringBuffer buffer, final String fieldName, final int[] array, final Boolean fullDetail) {
10191028 appendFieldStart(buffer, fieldName);
10201029
10211030 if (array == null) {
10401049 * @param array the array to add to the <code>toString</code>,
10411050 * not <code>null</code>
10421051 */
1043 protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {
1052 protected void appendDetail(final StringBuffer buffer, final String fieldName, final int[] array) {
10441053 buffer.append(arrayStart);
10451054 for (int i = 0; i < array.length; i++) {
10461055 if (i > 0) {
10601069 * @param array the array to add to the <code>toString</code>,
10611070 * not <code>null</code>
10621071 */
1063 protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {
1072 protected void appendSummary(final StringBuffer buffer, final String fieldName, final int[] array) {
10641073 appendSummarySize(buffer, fieldName, array.length);
10651074 }
10661075
10761085 * @param fullDetail <code>true</code> for detail, <code>false</code>
10771086 * for summary info, <code>null</code> for style decides
10781087 */
1079 public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {
1088 public void append(final StringBuffer buffer, final String fieldName, final short[] array, final Boolean fullDetail) {
10801089 appendFieldStart(buffer, fieldName);
10811090
10821091 if (array == null) {
11011110 * @param array the array to add to the <code>toString</code>,
11021111 * not <code>null</code>
11031112 */
1104 protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {
1113 protected void appendDetail(final StringBuffer buffer, final String fieldName, final short[] array) {
11051114 buffer.append(arrayStart);
11061115 for (int i = 0; i < array.length; i++) {
11071116 if (i > 0) {
11211130 * @param array the array to add to the <code>toString</code>,
11221131 * not <code>null</code>
11231132 */
1124 protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {
1133 protected void appendSummary(final StringBuffer buffer, final String fieldName, final short[] array) {
11251134 appendSummarySize(buffer, fieldName, array.length);
11261135 }
11271136
11371146 * @param fullDetail <code>true</code> for detail, <code>false</code>
11381147 * for summary info, <code>null</code> for style decides
11391148 */
1140 public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {
1149 public void append(final StringBuffer buffer, final String fieldName, final byte[] array, final Boolean fullDetail) {
11411150 appendFieldStart(buffer, fieldName);
11421151
11431152 if (array == null) {
11621171 * @param array the array to add to the <code>toString</code>,
11631172 * not <code>null</code>
11641173 */
1165 protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {
1174 protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte[] array) {
11661175 buffer.append(arrayStart);
11671176 for (int i = 0; i < array.length; i++) {
11681177 if (i > 0) {
11821191 * @param array the array to add to the <code>toString</code>,
11831192 * not <code>null</code>
11841193 */
1185 protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {
1194 protected void appendSummary(final StringBuffer buffer, final String fieldName, final byte[] array) {
11861195 appendSummarySize(buffer, fieldName, array.length);
11871196 }
11881197
11981207 * @param fullDetail <code>true</code> for detail, <code>false</code>
11991208 * for summary info, <code>null</code> for style decides
12001209 */
1201 public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {
1210 public void append(final StringBuffer buffer, final String fieldName, final char[] array, final Boolean fullDetail) {
12021211 appendFieldStart(buffer, fieldName);
12031212
12041213 if (array == null) {
12231232 * @param array the array to add to the <code>toString</code>,
12241233 * not <code>null</code>
12251234 */
1226 protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {
1235 protected void appendDetail(final StringBuffer buffer, final String fieldName, final char[] array) {
12271236 buffer.append(arrayStart);
12281237 for (int i = 0; i < array.length; i++) {
12291238 if (i > 0) {
12431252 * @param array the array to add to the <code>toString</code>,
12441253 * not <code>null</code>
12451254 */
1246 protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {
1255 protected void appendSummary(final StringBuffer buffer, final String fieldName, final char[] array) {
12471256 appendSummarySize(buffer, fieldName, array.length);
12481257 }
12491258
12591268 * @param fullDetail <code>true</code> for detail, <code>false</code>
12601269 * for summary info, <code>null</code> for style decides
12611270 */
1262 public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {
1271 public void append(final StringBuffer buffer, final String fieldName, final double[] array, final Boolean fullDetail) {
12631272 appendFieldStart(buffer, fieldName);
12641273
12651274 if (array == null) {
12841293 * @param array the array to add to the <code>toString</code>,
12851294 * not <code>null</code>
12861295 */
1287 protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {
1296 protected void appendDetail(final StringBuffer buffer, final String fieldName, final double[] array) {
12881297 buffer.append(arrayStart);
12891298 for (int i = 0; i < array.length; i++) {
12901299 if (i > 0) {
13041313 * @param array the array to add to the <code>toString</code>,
13051314 * not <code>null</code>
13061315 */
1307 protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {
1316 protected void appendSummary(final StringBuffer buffer, final String fieldName, final double[] array) {
13081317 appendSummarySize(buffer, fieldName, array.length);
13091318 }
13101319
13201329 * @param fullDetail <code>true</code> for detail, <code>false</code>
13211330 * for summary info, <code>null</code> for style decides
13221331 */
1323 public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {
1332 public void append(final StringBuffer buffer, final String fieldName, final float[] array, final Boolean fullDetail) {
13241333 appendFieldStart(buffer, fieldName);
13251334
13261335 if (array == null) {
13451354 * @param array the array to add to the <code>toString</code>,
13461355 * not <code>null</code>
13471356 */
1348 protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {
1357 protected void appendDetail(final StringBuffer buffer, final String fieldName, final float[] array) {
13491358 buffer.append(arrayStart);
13501359 for (int i = 0; i < array.length; i++) {
13511360 if (i > 0) {
13651374 * @param array the array to add to the <code>toString</code>,
13661375 * not <code>null</code>
13671376 */
1368 protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {
1377 protected void appendSummary(final StringBuffer buffer, final String fieldName, final float[] array) {
13691378 appendSummarySize(buffer, fieldName, array.length);
13701379 }
13711380
13811390 * @param fullDetail <code>true</code> for detail, <code>false</code>
13821391 * for summary info, <code>null</code> for style decides
13831392 */
1384 public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {
1393 public void append(final StringBuffer buffer, final String fieldName, final boolean[] array, final Boolean fullDetail) {
13851394 appendFieldStart(buffer, fieldName);
13861395
13871396 if (array == null) {
14061415 * @param array the array to add to the <code>toString</code>,
14071416 * not <code>null</code>
14081417 */
1409 protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {
1418 protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean[] array) {
14101419 buffer.append(arrayStart);
14111420 for (int i = 0; i < array.length; i++) {
14121421 if (i > 0) {
14261435 * @param array the array to add to the <code>toString</code>,
14271436 * not <code>null</code>
14281437 */
1429 protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {
1438 protected void appendSummary(final StringBuffer buffer, final String fieldName, final boolean[] array) {
14301439 appendSummarySize(buffer, fieldName, array.length);
14311440 }
14321441
14381447 * @param buffer the <code>StringBuffer</code> to populate
14391448 * @param object the <code>Object</code> whose name to output
14401449 */
1441 protected void appendClassName(StringBuffer buffer, Object object) {
1450 protected void appendClassName(final StringBuffer buffer, final Object object) {
14421451 if (useClassName && object != null) {
14431452 register(object);
14441453 if (useShortClassName) {
14551464 * @param buffer the <code>StringBuffer</code> to populate
14561465 * @param object the <code>Object</code> whose id to output
14571466 */
1458 protected void appendIdentityHashCode(StringBuffer buffer, Object object) {
1467 protected void appendIdentityHashCode(final StringBuffer buffer, final Object object) {
14591468 if (this.isUseIdentityHashCode() && object!=null) {
14601469 register(object);
14611470 buffer.append('@');
14681477 *
14691478 * @param buffer the <code>StringBuffer</code> to populate
14701479 */
1471 protected void appendContentStart(StringBuffer buffer) {
1480 protected void appendContentStart(final StringBuffer buffer) {
14721481 buffer.append(contentStart);
14731482 }
14741483
14771486 *
14781487 * @param buffer the <code>StringBuffer</code> to populate
14791488 */
1480 protected void appendContentEnd(StringBuffer buffer) {
1489 protected void appendContentEnd(final StringBuffer buffer) {
14811490 buffer.append(contentEnd);
14821491 }
14831492
14891498 * @param buffer the <code>StringBuffer</code> to populate
14901499 * @param fieldName the field name, typically not used as already appended
14911500 */
1492 protected void appendNullText(StringBuffer buffer, String fieldName) {
1501 protected void appendNullText(final StringBuffer buffer, final String fieldName) {
14931502 buffer.append(nullText);
14941503 }
14951504
14981507 *
14991508 * @param buffer the <code>StringBuffer</code> to populate
15001509 */
1501 protected void appendFieldSeparator(StringBuffer buffer) {
1510 protected void appendFieldSeparator(final StringBuffer buffer) {
15021511 buffer.append(fieldSeparator);
15031512 }
15041513
15081517 * @param buffer the <code>StringBuffer</code> to populate
15091518 * @param fieldName the field name
15101519 */
1511 protected void appendFieldStart(StringBuffer buffer, String fieldName) {
1520 protected void appendFieldStart(final StringBuffer buffer, final String fieldName) {
15121521 if (useFieldNames && fieldName != null) {
15131522 buffer.append(fieldName);
15141523 buffer.append(fieldNameValueSeparator);
15211530 * @param buffer the <code>StringBuffer</code> to populate
15221531 * @param fieldName the field name, typically not used as already appended
15231532 */
1524 protected void appendFieldEnd(StringBuffer buffer, String fieldName) {
1533 protected void appendFieldEnd(final StringBuffer buffer, final String fieldName) {
15251534 appendFieldSeparator(buffer);
15261535 }
15271536
15401549 * @param fieldName the field name, typically not used as already appended
15411550 * @param size the size to append
15421551 */
1543 protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {
1552 protected void appendSummarySize(final StringBuffer buffer, final String fieldName, final int size) {
15441553 buffer.append(sizeStartText);
15451554 buffer.append(size);
15461555 buffer.append(sizeEndText);
15601569 * @param fullDetailRequest the detail level requested
15611570 * @return whether full detail is to be shown
15621571 */
1563 protected boolean isFullDetail(Boolean fullDetailRequest) {
1572 protected boolean isFullDetail(final Boolean fullDetailRequest) {
15641573 if (fullDetailRequest == null) {
15651574 return defaultFullDetail;
15661575 }
15761585 * @param cls the <code>Class</code> to get the short name of
15771586 * @return the short name
15781587 */
1579 protected String getShortClassName(Class<?> cls) {
1588 protected String getShortClassName(final Class<?> cls) {
15801589 return ClassUtils.getShortClassName(cls);
15811590 }
15821591
15991608 *
16001609 * @param useClassName the new useClassName flag
16011610 */
1602 protected void setUseClassName(boolean useClassName) {
1611 protected void setUseClassName(final boolean useClassName) {
16031612 this.useClassName = useClassName;
16041613 }
16051614
16211630 * @param useShortClassName the new useShortClassName flag
16221631 * @since 2.0
16231632 */
1624 protected void setUseShortClassName(boolean useShortClassName) {
1633 protected void setUseShortClassName(final boolean useShortClassName) {
16251634 this.useShortClassName = useShortClassName;
16261635 }
16271636
16411650 *
16421651 * @param useIdentityHashCode the new useIdentityHashCode flag
16431652 */
1644 protected void setUseIdentityHashCode(boolean useIdentityHashCode) {
1653 protected void setUseIdentityHashCode(final boolean useIdentityHashCode) {
16451654 this.useIdentityHashCode = useIdentityHashCode;
16461655 }
16471656
16611670 *
16621671 * @param useFieldNames the new useFieldNames flag
16631672 */
1664 protected void setUseFieldNames(boolean useFieldNames) {
1673 protected void setUseFieldNames(final boolean useFieldNames) {
16651674 this.useFieldNames = useFieldNames;
16661675 }
16671676
16831692 *
16841693 * @param defaultFullDetail the new defaultFullDetail flag
16851694 */
1686 protected void setDefaultFullDetail(boolean defaultFullDetail) {
1695 protected void setDefaultFullDetail(final boolean defaultFullDetail) {
16871696 this.defaultFullDetail = defaultFullDetail;
16881697 }
16891698
17031712 *
17041713 * @param arrayContentDetail the new arrayContentDetail flag
17051714 */
1706 protected void setArrayContentDetail(boolean arrayContentDetail) {
1715 protected void setArrayContentDetail(final boolean arrayContentDetail) {
17071716 this.arrayContentDetail = arrayContentDetail;
17081717 }
17091718
19091918 * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag
19101919 * @since 2.0
19111920 */
1912 protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {
1921 protected void setFieldSeparatorAtStart(final boolean fieldSeparatorAtStart) {
19131922 this.fieldSeparatorAtStart = fieldSeparatorAtStart;
19141923 }
19151924
19331942 * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag
19341943 * @since 2.0
19351944 */
1936 protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {
1945 protected void setFieldSeparatorAtEnd(final boolean fieldSeparatorAtEnd) {
19371946 this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;
19381947 }
19391948
21952204 }
21962205
21972206 }
2207
2208 //----------------------------------------------------------------------------
21982209
21992210 /**
22002211 * <p><code>ToStringStyle</code> that does not print out the
6060 * </p>
6161 *
6262 * @since 3.0
63 * @version $Id: AtomicInitializer.java 1088899 2011-04-05 05:31:27Z bayard $
63 * @version $Id: AtomicInitializer.java 1309977 2012-04-05 17:53:39Z ggregory $
6464 * @param <T> the type of the object managed by this initializer class
6565 */
6666 public abstract class AtomicInitializer<T> implements ConcurrentInitializer<T> {
7676 * @throws ConcurrentException if an error occurred during initialization of
7777 * the object
7878 */
79 @Override
7980 public T get() throws ConcurrentException {
8081 T result = reference.get();
8182
4949 * </p>
5050 *
5151 * @since 3.0
52 * @version $Id: AtomicSafeInitializer.java 1088899 2011-04-05 05:31:27Z bayard $
52 * @version $Id: AtomicSafeInitializer.java 1309977 2012-04-05 17:53:39Z ggregory $
5353 * @param <T> the type of the object managed by this initializer class
5454 */
5555 public abstract class AtomicSafeInitializer<T> implements
6868 * @throws ConcurrentException if the initialization of the object causes an
6969 * exception
7070 */
71 @Override
7172 public final T get() throws ConcurrentException {
7273 T result;
7374
7979 * </p>
8080 *
8181 * @since 3.0
82 * @version $Id: BackgroundInitializer.java 1082044 2011-03-16 04:26:58Z bayard $
82 * @version $Id: BackgroundInitializer.java 1436770 2013-01-22 07:09:45Z ggregory $
8383 * @param <T> the type of the object managed by this initializer class
8484 */
8585 public abstract class BackgroundInitializer<T> implements
8686 ConcurrentInitializer<T> {
8787 /** The external executor service for executing tasks. */
88 private ExecutorService externalExecutor;
88 private ExecutorService externalExecutor; // @GuardedBy("this")
8989
9090 /** A reference to the executor service that is actually used. */
91 private ExecutorService executor;
91 private ExecutorService executor; // @GuardedBy("this")
9292
9393 /** Stores the handle to the background task. */
94 private Future<T> future;
94 private Future<T> future; // @GuardedBy("this")
9595
9696 /**
9797 * Creates a new instance of {@code BackgroundInitializer}. No external
111111 * @param exec an external {@code ExecutorService} to be used for task
112112 * execution
113113 */
114 protected BackgroundInitializer(ExecutorService exec) {
114 protected BackgroundInitializer(final ExecutorService exec) {
115115 setExternalExecutor(exec);
116116 }
117117
150150 * started
151151 */
152152 public final synchronized void setExternalExecutor(
153 ExecutorService externalExecutor) {
153 final ExecutorService externalExecutor) {
154154 if (isStarted()) {
155155 throw new IllegalStateException(
156156 "Cannot set ExecutorService after start()!");
205205 * background processing
206206 * @throws IllegalStateException if {@link #start()} has not been called
207207 */
208 @Override
208209 public T get() throws ConcurrentException {
209210 try {
210211 return getFuture().get();
211 } catch (ExecutionException execex) {
212 } catch (final ExecutionException execex) {
212213 ConcurrentUtils.handleCause(execex);
213214 return null; // should not be reached
214 } catch (InterruptedException iex) {
215 } catch (final InterruptedException iex) {
215216 // reset interrupted state
216217 Thread.currentThread().interrupt();
217218 throw new ConcurrentException(iex);
285286 * task
286287 * @return a task for the background initialization
287288 */
288 private Callable<T> createTask(ExecutorService execDestroy) {
289 private Callable<T> createTask(final ExecutorService execDestroy) {
289290 return new InitializationTask(execDestroy);
290291 }
291292
309310 *
310311 * @param exec the {@code ExecutorService}
311312 */
312 public InitializationTask(ExecutorService exec) {
313 public InitializationTask(final ExecutorService exec) {
313314 execFinally = exec;
314315 }
315316
319320 * @return the result object
320321 * @throws Exception if an error occurs
321322 */
323 @Override
322324 public T call() throws Exception {
323325 try {
324326 return initialize();
8484 * </p>
8585 *
8686 * @since 3.0
87 * @version $Id: BasicThreadFactory.java 1079423 2011-03-08 16:38:09Z sebb $
87 * @version $Id: BasicThreadFactory.java 1436770 2013-01-22 07:09:45Z ggregory $
8888 */
8989 public class BasicThreadFactory implements ThreadFactory {
9090 /** A counter for the threads created by this factory. */
111111 *
112112 * @param builder the {@code Builder} object
113113 */
114 private BasicThreadFactory(Builder builder) {
114 private BasicThreadFactory(final Builder builder) {
115115 if (builder.wrappedFactory == null) {
116116 wrappedFactory = Executors.defaultThreadFactory();
117117 } else {
199199 * @param r the {@code Runnable} to be executed by the new thread
200200 * @return the newly created thread
201201 */
202 public Thread newThread(Runnable r) {
203 Thread t = getWrappedFactory().newThread(r);
202 @Override
203 public Thread newThread(final Runnable r) {
204 final Thread t = getWrappedFactory().newThread(r);
204205 initializeThread(t);
205206
206207 return t;
214215 *
215216 * @param t the thread to be initialized
216217 */
217 private void initializeThread(Thread t) {
218 private void initializeThread(final Thread t) {
218219
219220 if (getNamingPattern() != null) {
220 Long count = Long.valueOf(threadCounter.incrementAndGet());
221 final Long count = Long.valueOf(threadCounter.incrementAndGet());
221222 t.setName(String.format(getNamingPattern(), count));
222223 }
223224
247248 * BasicThreadFactory} for a usage example.
248249 * </p>
249250 *
250 * @version $Id: BasicThreadFactory.java 1079423 2011-03-08 16:38:09Z sebb $
251 * @version $Id: BasicThreadFactory.java 1436770 2013-01-22 07:09:45Z ggregory $
251252 */
252253 public static class Builder
253254 implements org.apache.commons.lang3.builder.Builder<BasicThreadFactory> {
277278 * @throws NullPointerException if the passed in {@code ThreadFactory}
278279 * is <b>null</b>
279280 */
280 public Builder wrappedFactory(ThreadFactory factory) {
281 public Builder wrappedFactory(final ThreadFactory factory) {
281282 if (factory == null) {
282283 throw new NullPointerException(
283284 "Wrapped ThreadFactory must not be null!");
295296 * @return a reference to this {@code Builder}
296297 * @throws NullPointerException if the naming pattern is <b>null</b>
297298 */
298 public Builder namingPattern(String pattern) {
299 public Builder namingPattern(final String pattern) {
299300 if (pattern == null) {
300301 throw new NullPointerException(
301302 "Naming pattern must not be null!");
313314 * @param f the value of the daemon flag
314315 * @return a reference to this {@code Builder}
315316 */
316 public Builder daemon(boolean f) {
317 public Builder daemon(final boolean f) {
317318 daemonFlag = Boolean.valueOf(f);
318319 return this;
319320 }
325326 * @param prio the priority
326327 * @return a reference to this {@code Builder}
327328 */
328 public Builder priority(int prio) {
329 public Builder priority(final int prio) {
329330 priority = Integer.valueOf(prio);
330331 return this;
331332 }
340341 * @throws NullPointerException if the exception handler is <b>null</b>
341342 */
342343 public Builder uncaughtExceptionHandler(
343 Thread.UncaughtExceptionHandler handler) {
344 final Thread.UncaughtExceptionHandler handler) {
344345 if (handler == null) {
345346 throw new NullPointerException(
346347 "Uncaught exception handler must not be null!");
371372 *
372373 * @return the new {@code BasicThreadFactory}
373374 */
375 @Override
374376 public BasicThreadFactory build() {
375 BasicThreadFactory factory = new BasicThreadFactory(this);
377 final BasicThreadFactory factory = new BasicThreadFactory(this);
376378 reset();
377379 return factory;
378380 }
6161 * </p>
6262 *
6363 * @since 3.0
64 * @version $Id: CallableBackgroundInitializer.java 1082044 2011-03-16 04:26:58Z bayard $
64 * @version $Id: CallableBackgroundInitializer.java 1436768 2013-01-22 07:07:42Z ggregory $
6565 * @param <T> the type of the object managed by this initializer class
6666 */
6767 public class CallableBackgroundInitializer<T> extends BackgroundInitializer<T> {
7575 * @param call the {@code Callable} (must not be <b>null</b>)
7676 * @throws IllegalArgumentException if the {@code Callable} is <b>null</b>
7777 */
78 public CallableBackgroundInitializer(Callable<T> call) {
78 public CallableBackgroundInitializer(final Callable<T> call) {
7979 checkCallable(call);
8080 callable = call;
8181 }
9191 * execution
9292 * @throws IllegalArgumentException if the {@code Callable} is <b>null</b>
9393 */
94 public CallableBackgroundInitializer(Callable<T> call, ExecutorService exec) {
94 public CallableBackgroundInitializer(final Callable<T> call, final ExecutorService exec) {
9595 super(exec);
9696 checkCallable(call);
9797 callable = call;
117117 * @param call the object to check
118118 * @throws IllegalArgumentException if the {@code Callable} is <b>null</b>
119119 */
120 private void checkCallable(Callable<T> call) {
120 private void checkCallable(final Callable<T> call) {
121121 if (call == null) {
122122 throw new IllegalArgumentException("Callable must not be null!");
123123 }
2929 * </p>
3030 *
3131 * @since 3.0
32 * @version $Id: ConcurrentException.java 1088899 2011-04-05 05:31:27Z bayard $
32 * @version $Id: ConcurrentException.java 1436768 2013-01-22 07:07:42Z ggregory $
3333 */
3434 public class ConcurrentException extends Exception {
3535 /**
5151 * @param cause the cause of this exception
5252 * @throws IllegalArgumentException if the cause is not a checked exception
5353 */
54 public ConcurrentException(Throwable cause) {
54 public ConcurrentException(final Throwable cause) {
5555 super(ConcurrentUtils.checkedException(cause));
5656 }
5757
6363 * @param cause the cause of this exception
6464 * @throws IllegalArgumentException if the cause is not a checked exception
6565 */
66 public ConcurrentException(String msg, Throwable cause) {
66 public ConcurrentException(final String msg, final Throwable cause) {
6767 super(msg, ConcurrentUtils.checkedException(cause));
6868 }
6969 }
3030 * </p>
3131 *
3232 * @since 3.0
33 * @version $Id: ConcurrentRuntimeException.java 1088899 2011-04-05 05:31:27Z bayard $
33 * @version $Id: ConcurrentRuntimeException.java 1436768 2013-01-22 07:07:42Z ggregory $
3434 */
3535 public class ConcurrentRuntimeException extends RuntimeException {
3636 /**
5353 * @param cause the cause of this exception
5454 * @throws IllegalArgumentException if the cause is not a checked exception
5555 */
56 public ConcurrentRuntimeException(Throwable cause) {
56 public ConcurrentRuntimeException(final Throwable cause) {
5757 super(ConcurrentUtils.checkedException(cause));
5858 }
5959
6565 * @param cause the cause of this exception
6666 * @throws IllegalArgumentException if the cause is not a checked exception
6767 */
68 public ConcurrentRuntimeException(String msg, Throwable cause) {
68 public ConcurrentRuntimeException(final String msg, final Throwable cause) {
6969 super(msg, ConcurrentUtils.checkedException(cause));
7070 }
7171 }
2727 * </p>
2828 *
2929 * @since 3.0
30 * @version $Id: ConcurrentUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
30 * @version $Id: ConcurrentUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3131 */
3232 public class ConcurrentUtils {
3333
5656 * @param ex the exception to be processed
5757 * @return a {@code ConcurrentException} with the checked cause
5858 */
59 public static ConcurrentException extractCause(ExecutionException ex) {
59 public static ConcurrentException extractCause(final ExecutionException ex) {
6060 if (ex == null || ex.getCause() == null) {
6161 return null;
6262 }
7878 * @return a {@code ConcurrentRuntimeException} with the checked cause
7979 */
8080 public static ConcurrentRuntimeException extractCauseUnchecked(
81 ExecutionException ex) {
81 final ExecutionException ex) {
8282 if (ex == null || ex.getCause() == null) {
8383 return null;
8484 }
100100 * @throws ConcurrentException if the cause of the {@code
101101 * ExecutionException} is a checked exception
102102 */
103 public static void handleCause(ExecutionException ex)
103 public static void handleCause(final ExecutionException ex)
104104 throws ConcurrentException {
105 ConcurrentException cex = extractCause(ex);
105 final ConcurrentException cex = extractCause(ex);
106106
107107 if (cex != null) {
108108 throw cex;
122122 * ExecutionException} is a checked exception; this exception is then
123123 * wrapped in the thrown runtime exception
124124 */
125 public static void handleCauseUnchecked(ExecutionException ex) {
126 ConcurrentRuntimeException crex = extractCauseUnchecked(ex);
125 public static void handleCauseUnchecked(final ExecutionException ex) {
126 final ConcurrentRuntimeException crex = extractCauseUnchecked(ex);
127127
128128 if (crex != null) {
129129 throw crex;
139139 * @throws IllegalArgumentException if the {@code Throwable} is not a
140140 * checked exception
141141 */
142 static Throwable checkedException(Throwable ex) {
142 static Throwable checkedException(final Throwable ex) {
143143 if (ex != null && !(ex instanceof RuntimeException)
144144 && !(ex instanceof Error)) {
145145 return ex;
154154 *
155155 * @param ex the exception in question
156156 */
157 private static void throwCause(ExecutionException ex) {
157 private static void throwCause(final ExecutionException ex) {
158158 if (ex.getCause() instanceof RuntimeException) {
159159 throw (RuntimeException) ex.getCause();
160160 }
178178 * @throws ConcurrentException if the {@code ConcurrentInitializer} throws
179179 * an exception
180180 */
181 public static <T> T initialize(ConcurrentInitializer<T> initializer)
181 public static <T> T initialize(final ConcurrentInitializer<T> initializer)
182182 throws ConcurrentException {
183183 return initializer != null ? initializer.get() : null;
184184 }
196196 * @return the object managed by the {@code ConcurrentInitializer}
197197 * @throws ConcurrentRuntimeException if the initializer throws an exception
198198 */
199 public static <T> T initializeUnchecked(ConcurrentInitializer<T> initializer) {
199 public static <T> T initializeUnchecked(final ConcurrentInitializer<T> initializer) {
200200 try {
201201 return initialize(initializer);
202 } catch (ConcurrentException cex) {
202 } catch (final ConcurrentException cex) {
203203 throw new ConcurrentRuntimeException(cex.getCause());
204204 }
205205 }
237237 * @param value the value to be added
238238 * @return the value stored in the map after this operation
239239 */
240 public static <K, V> V putIfAbsent(ConcurrentMap<K, V> map, K key, V value) {
240 public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value) {
241241 if (map == null) {
242242 return null;
243243 }
244244
245 V result = map.putIfAbsent(key, value);
245 final V result = map.putIfAbsent(key, value);
246246 return result != null ? result : value;
247247 }
248248
266266 * not be the object created by the {@link ConcurrentInitializer}
267267 * @throws ConcurrentException if the initializer throws an exception
268268 */
269 public static <K, V> V createIfAbsent(ConcurrentMap<K, V> map, K key,
270 ConcurrentInitializer<V> init) throws ConcurrentException {
269 public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key,
270 final ConcurrentInitializer<V> init) throws ConcurrentException {
271271 if (map == null || init == null) {
272272 return null;
273273 }
274274
275 V value = map.get(key);
275 final V value = map.get(key);
276276 if (value == null) {
277277 return putIfAbsent(map, key, init.get());
278278 }
294294 * not be the object created by the {@link ConcurrentInitializer}
295295 * @throws ConcurrentRuntimeException if the initializer throws an exception
296296 */
297 public static <K, V> V createIfAbsentUnchecked(ConcurrentMap<K, V> map,
298 K key, ConcurrentInitializer<V> init) {
297 public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map,
298 final K key, final ConcurrentInitializer<V> init) {
299299 try {
300300 return createIfAbsent(map, key, init);
301 } catch (ConcurrentException cex) {
301 } catch (final ConcurrentException cex) {
302302 throw new ConcurrentRuntimeException(cex.getCause());
303303 }
304304 }
319319 * @param value the constant value to return, may be null
320320 * @return an instance of Future that will return the value, never null
321321 */
322 public static <T> Future<T> constantFuture(T value) {
322 public static <T> Future<T> constantFuture(final T value) {
323323 return new ConstantFuture<T>(value);
324324 }
325325
337337 *
338338 * @param value the value (may be <b>null</b>)
339339 */
340 ConstantFuture(T value) {
340 ConstantFuture(final T value) {
341341 this.value = value;
342342 }
343343
346346 * the constant object managed by this {@code Future} implementation is
347347 * always available.
348348 */
349 @Override
349350 public boolean isDone() {
350351 return true;
351352 }
353354 /**
354355 * {@inheritDoc} This implementation just returns the constant value.
355356 */
357 @Override
356358 public T get() {
357359 return value;
358360 }
361363 * {@inheritDoc} This implementation just returns the constant value; it
362364 * does not block, therefore the timeout has no meaning.
363365 */
364 public T get(long timeout, TimeUnit unit) {
366 @Override
367 public T get(final long timeout, final TimeUnit unit) {
365368 return value;
366369 }
367370
369372 * {@inheritDoc} This implementation always returns <b>false</b>; there
370373 * is no background process which could be cancelled.
371374 */
375 @Override
372376 public boolean isCancelled() {
373377 return false;
374378 }
377381 * {@inheritDoc} The cancel operation is not supported. This
378382 * implementation always returns <b>false</b>.
379383 */
380 public boolean cancel(boolean mayInterruptIfRunning) {
384 @Override
385 public boolean cancel(final boolean mayInterruptIfRunning) {
381386 return false;
382387 }
383388 }
3434 * </p>
3535 *
3636 * @since 3.0
37 * @version $Id: ConstantInitializer.java 1199894 2011-11-09 17:53:59Z ggregory $
37 * @version $Id: ConstantInitializer.java 1436770 2013-01-22 07:09:45Z ggregory $
3838 * @param <T> the type of the object managed by this initializer
3939 */
4040 public class ConstantInitializer<T> implements ConcurrentInitializer<T> {
5353 *
5454 * @param obj the object to be managed by this initializer
5555 */
56 public ConstantInitializer(T obj) {
56 public ConstantInitializer(final T obj) {
5757 object = obj;
5858 }
5959
7575 * @return the object managed by this initializer
7676 * @throws ConcurrentException if an error occurs
7777 */
78 @Override
7879 public T get() throws ConcurrentException {
7980 return getObject();
8081 }
100101 * @return a flag whether the objects are equal
101102 */
102103 @Override
103 public boolean equals(Object obj) {
104 public boolean equals(final Object obj) {
104105 if (this == obj) {
105106 return true;
106107 }
108109 return false;
109110 }
110111
111 ConstantInitializer<?> c = (ConstantInitializer<?>) obj;
112 final ConstantInitializer<?> c = (ConstantInitializer<?>) obj;
112113 return ObjectUtils.equals(getObject(), c.getObject());
113114 }
114115
7272 * </p>
7373 *
7474 * @since 3.0
75 * @version $Id: LazyInitializer.java 1088899 2011-04-05 05:31:27Z bayard $
75 * @version $Id: LazyInitializer.java 1309977 2012-04-05 17:53:39Z ggregory $
7676 * @param <T> the type of the object managed by this initializer class
7777 */
7878 public abstract class LazyInitializer<T> implements ConcurrentInitializer<T> {
8787 * @throws ConcurrentException if an error occurred during initialization of
8888 * the object
8989 */
90 @Override
9091 public T get() throws ConcurrentException {
9192 // use a temporary variable to reduce the number of reads of the
9293 // volatile field
9191 * </p>
9292 *
9393 * @since 3.0
94 * @version $Id: MultiBackgroundInitializer.java 1082301 2011-03-16 21:02:15Z oheger $
94 * @version $Id: MultiBackgroundInitializer.java 1436770 2013-01-22 07:09:45Z ggregory $
9595 */
9696 public class MultiBackgroundInitializer
9797 extends
114114 * @param exec the {@code ExecutorService} for executing the background
115115 * tasks
116116 */
117 public MultiBackgroundInitializer(ExecutorService exec) {
117 public MultiBackgroundInitializer(final ExecutorService exec) {
118118 super(exec);
119119 }
120120
130130 * @throws IllegalArgumentException if a required parameter is missing
131131 * @throws IllegalStateException if {@code start()} has already been called
132132 */
133 public void addInitializer(String name, BackgroundInitializer<?> init) {
133 public void addInitializer(final String name, final BackgroundInitializer<?> init) {
134134 if (name == null) {
135135 throw new IllegalArgumentException(
136136 "Name of child initializer must not be null!");
163163 protected int getTaskCount() {
164164 int result = 1;
165165
166 for (BackgroundInitializer<?> bi : childInitializers.values()) {
166 for (final BackgroundInitializer<?> bi : childInitializers.values()) {
167167 result += bi.getTaskCount();
168168 }
169169
190190 }
191191
192192 // start the child initializers
193 ExecutorService exec = getActiveExecutor();
194 for (BackgroundInitializer<?> bi : inits.values()) {
193 final ExecutorService exec = getActiveExecutor();
194 for (final BackgroundInitializer<?> bi : inits.values()) {
195195 if (bi.getExternalExecutor() == null) {
196196 // share the executor service if necessary
197197 bi.setExternalExecutor(exec);
200200 }
201201
202202 // collect the results
203 Map<String, Object> results = new HashMap<String, Object>();
204 Map<String, ConcurrentException> excepts = new HashMap<String, ConcurrentException>();
205 for (Map.Entry<String, BackgroundInitializer<?>> e : inits.entrySet()) {
203 final Map<String, Object> results = new HashMap<String, Object>();
204 final Map<String, ConcurrentException> excepts = new HashMap<String, ConcurrentException>();
205 for (final Map.Entry<String, BackgroundInitializer<?>> e : inits.entrySet()) {
206206 try {
207207 results.put(e.getKey(), e.getValue().get());
208 } catch (ConcurrentException cex) {
208 } catch (final ConcurrentException cex) {
209209 excepts.put(e.getKey(), cex);
210210 }
211211 }
243243 * @param excepts the exceptions
244244 */
245245 private MultiBackgroundInitializerResults(
246 Map<String, BackgroundInitializer<?>> inits,
247 Map<String, Object> results,
248 Map<String, ConcurrentException> excepts) {
246 final Map<String, BackgroundInitializer<?>> inits,
247 final Map<String, Object> results,
248 final Map<String, ConcurrentException> excepts) {
249249 initializers = inits;
250250 resultObjects = results;
251251 exceptions = excepts;
259259 * @return the {@code BackgroundInitializer} with this name
260260 * @throws NoSuchElementException if the name cannot be resolved
261261 */
262 public BackgroundInitializer<?> getInitializer(String name) {
262 public BackgroundInitializer<?> getInitializer(final String name) {
263263 return checkName(name);
264264 }
265265
275275 * BackgroundInitializer}
276276 * @throws NoSuchElementException if the name cannot be resolved
277277 */
278 public Object getResultObject(String name) {
278 public Object getResultObject(final String name) {
279279 checkName(name);
280280 return resultObjects.get(name);
281281 }
288288 * @return a flag whether this initializer caused an exception
289289 * @throws NoSuchElementException if the name cannot be resolved
290290 */
291 public boolean isException(String name) {
291 public boolean isException(final String name) {
292292 checkName(name);
293293 return exceptions.containsKey(name);
294294 }
303303 * @return the exception thrown by this initializer
304304 * @throws NoSuchElementException if the name cannot be resolved
305305 */
306 public ConcurrentException getException(String name) {
306 public ConcurrentException getException(final String name) {
307307 checkName(name);
308308 return exceptions.get(name);
309309 }
338338 * @return the initializer with this name
339339 * @throws NoSuchElementException if the name is unknown
340340 */
341 private BackgroundInitializer<?> checkName(String name) {
342 BackgroundInitializer<?> init = initializers.get(name);
341 private BackgroundInitializer<?> checkName(final String name) {
342 final BackgroundInitializer<?> init = initializers.get(name);
343343 if (init == null) {
344344 throw new NoSuchElementException(
345345 "No child initializer with name " + name);
122122 * </p>
123123 *
124124 * @since 3.0
125 * @version $Id: TimedSemaphore.java 1199894 2011-11-09 17:53:59Z ggregory $
125 * @version $Id: TimedSemaphore.java 1436770 2013-01-22 07:09:45Z ggregory $
126126 */
127127 public class TimedSemaphore {
128128 /**
148148 private final boolean ownExecutor;
149149
150150 /** A future object representing the timer task. */
151 private ScheduledFuture<?> task;
151 private ScheduledFuture<?> task; // @GuardedBy("this")
152152
153153 /** Stores the total number of invocations of the acquire() method. */
154 private long totalAcquireCount;
154 private long totalAcquireCount; // @GuardedBy("this")
155155
156156 /**
157157 * The counter for the periods. This counter is increased every time a
158158 * period ends.
159159 */
160 private long periodCount;
160 private long periodCount; // @GuardedBy("this")
161161
162162 /** The limit. */
163 private int limit;
163 private int limit; // @GuardedBy("this")
164164
165165 /** The current counter. */
166 private int acquireCount;
166 private int acquireCount; // @GuardedBy("this")
167167
168168 /** The number of invocations of acquire() in the last period. */
169 private int lastCallsPerPeriod;
169 private int lastCallsPerPeriod; // @GuardedBy("this")
170170
171171 /** A flag whether shutdown() was called. */
172 private boolean shutdown;
172 private boolean shutdown; // @GuardedBy("this")
173173
174174 /**
175175 * Creates a new instance of {@link TimedSemaphore} and initializes it with
180180 * @param limit the limit for the semaphore
181181 * @throws IllegalArgumentException if the period is less or equals 0
182182 */
183 public TimedSemaphore(long timePeriod, TimeUnit timeUnit, int limit) {
183 public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit) {
184184 this(null, timePeriod, timeUnit, limit);
185185 }
186186
196196 * @param limit the limit for the semaphore
197197 * @throws IllegalArgumentException if the period is less or equals 0
198198 */
199 public TimedSemaphore(ScheduledExecutorService service, long timePeriod,
200 TimeUnit timeUnit, int limit) {
199 public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod,
200 final TimeUnit timeUnit, final int limit) {
201201 if (timePeriod <= 0) {
202202 throw new IllegalArgumentException("Time period must be greater 0!");
203203 }
209209 executorService = service;
210210 ownExecutor = false;
211211 } else {
212 ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(
212 final ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(
213213 THREAD_POOL_SIZE);
214214 s.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
215215 s.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
241241 *
242242 * @param limit the limit
243243 */
244 public final synchronized void setLimit(int limit) {
244 public final synchronized void setLimit(final int limit) {
245245 this.limit = limit;
246246 }
247247
399399 */
400400 protected ScheduledFuture<?> startTimer() {
401401 return getExecutorService().scheduleAtFixedRate(new Runnable() {
402 @Override
402403 public void run() {
403404 endOfPeriod();
404405 }
6060 * @param <L> the type of event listener that is supported by this proxy.
6161 *
6262 * @since 3.0
63 * @version $Id: EventListenerSupport.java 1082302 2011-03-16 21:08:27Z oheger $
63 * @version $Id: EventListenerSupport.java 1533570 2013-10-18 17:40:28Z sebb $
6464 */
6565 public class EventListenerSupport<L> implements Serializable {
6666
101101 * @throws IllegalArgumentException if <code>listenerInterface</code> is
102102 * not an interface.
103103 */
104 public static <T> EventListenerSupport<T> create(Class<T> listenerInterface) {
104 public static <T> EventListenerSupport<T> create(final Class<T> listenerInterface) {
105105 return new EventListenerSupport<T>(listenerInterface);
106106 }
107107
117117 * @throws IllegalArgumentException if <code>listenerInterface</code> is
118118 * not an interface.
119119 */
120 public EventListenerSupport(Class<L> listenerInterface) {
120 public EventListenerSupport(final Class<L> listenerInterface) {
121121 this(listenerInterface, Thread.currentThread().getContextClassLoader());
122122 }
123123
134134 * @throws IllegalArgumentException if <code>listenerInterface</code> is
135135 * not an interface.
136136 */
137 public EventListenerSupport(Class<L> listenerInterface, ClassLoader classLoader) {
137 public EventListenerSupport(final Class<L> listenerInterface, final ClassLoader classLoader) {
138138 this();
139139 Validate.notNull(listenerInterface, "Listener interface cannot be null.");
140140 Validate.notNull(classLoader, "ClassLoader cannot be null.");
174174 * @throws NullPointerException if <code>listener</code> is
175175 * <code>null</code>.
176176 */
177 public void addListener(L listener) {
177 public void addListener(final L listener) {
178178 Validate.notNull(listener, "Listener object cannot be null.");
179179 listeners.add(listener);
180180 }
196196 * @throws NullPointerException if <code>listener</code> is
197197 * <code>null</code>.
198198 */
199 public void removeListener(L listener) {
199 public void removeListener(final L listener) {
200200 Validate.notNull(listener, "Listener object cannot be null.");
201201 listeners.remove(listener);
202202 }
216216 * @param objectOutputStream the output stream
217217 * @throws IOException if an IO error occurs
218218 */
219 private void writeObject(ObjectOutputStream objectOutputStream) throws IOException {
220 ArrayList<L> serializableListeners = new ArrayList<L>();
219 private void writeObject(final ObjectOutputStream objectOutputStream) throws IOException {
220 final ArrayList<L> serializableListeners = new ArrayList<L>();
221221
222222 // don't just rely on instanceof Serializable:
223223 ObjectOutputStream testObjectOutputStream = new ObjectOutputStream(new ByteArrayOutputStream());
224 for (L listener : listeners) {
224 for (final L listener : listeners) {
225225 try {
226226 testObjectOutputStream.writeObject(listener);
227227 serializableListeners.add(listener);
228 } catch (IOException exception) {
228 } catch (final IOException exception) {
229229 //recreate test stream in case of indeterminate state
230230 testObjectOutputStream = new ObjectOutputStream(new ByteArrayOutputStream());
231231 }
243243 * @throws IOException if an IO error occurs
244244 * @throws ClassNotFoundException if the class cannot be resolved
245245 */
246 private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
247 @SuppressWarnings("unchecked")
248 L[] listeners = (L[]) objectInputStream.readObject();
249
250 this.listeners = new CopyOnWriteArrayList<L>(listeners);
251
252 @SuppressWarnings("unchecked")
253 Class<L> listenerInterface = (Class<L>) listeners.getClass().getComponentType();
246 private void readObject(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
247 @SuppressWarnings("unchecked") // Will throw CCE here if not correct
248 final
249 L[] srcListeners = (L[]) objectInputStream.readObject();
250
251 this.listeners = new CopyOnWriteArrayList<L>(srcListeners);
252
253 @SuppressWarnings("unchecked") // Will throw CCE here if not correct
254 final
255 Class<L> listenerInterface = (Class<L>) srcListeners.getClass().getComponentType();
254256
255257 initializeTransientFields(listenerInterface, Thread.currentThread().getContextClassLoader());
256258 }
260262 * @param listenerInterface the class of the listener interface
261263 * @param classLoader the class loader to be used
262264 */
263 private void initializeTransientFields(Class<L> listenerInterface, ClassLoader classLoader) {
264 @SuppressWarnings("unchecked")
265 private void initializeTransientFields(final Class<L> listenerInterface, final ClassLoader classLoader) {
266 @SuppressWarnings("unchecked") // Will throw CCE here if not correct
267 final
265268 L[] array = (L[]) Array.newInstance(listenerInterface, 0);
266269 this.prototypeArray = array;
267270 createProxy(listenerInterface, classLoader);
272275 * @param listenerInterface the class of the listener interface
273276 * @param classLoader the class loader to be used
274277 */
275 private void createProxy(Class<L> listenerInterface, ClassLoader classLoader) {
278 private void createProxy(final Class<L> listenerInterface, final ClassLoader classLoader) {
276279 proxy = listenerInterface.cast(Proxy.newProxyInstance(classLoader,
277280 new Class[] { listenerInterface }, createInvocationHandler()));
278281 }
290293 * An invocation handler used to dispatch the event(s) to all the listeners.
291294 */
292295 protected class ProxyInvocationHandler implements InvocationHandler {
293 /** Serialization version */
294 private static final long serialVersionUID = 1L;
295296
296297 /**
297298 * Propagates the method call to all registered listeners in place of
298299 * the proxy listener object.
299300 *
300 * @param proxy the proxy object representing a listener on which the
301 * invocation was called.
301 * @param unusedProxy the proxy object representing a listener on which the
302 * invocation was called; not used
302303 * @param method the listener method that will be called on all of the
303304 * listeners.
304305 * @param args event arguments to propagate to the listeners.
305306 * @return the result of the method call
306307 * @throws Throwable if an error occurs
307308 */
308 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
309 for (L listener : listeners) {
309 @Override
310 public Object invoke(final Object unusedProxy, final Method method, final Object[] args) throws Throwable {
311 for (final L listener : listeners) {
310312 method.invoke(listener, args);
311313 }
312314 return null;
3030 * Provides some useful event-based utility methods.
3131 *
3232 * @since 3.0
33 * @version $Id: EventUtils.java 1091072 2011-04-11 13:42:03Z mbenson $
33 * @version $Id: EventUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3434 */
3535 public class EventUtils {
3636
4444 *
4545 * @throws IllegalArgumentException if the object doesn't support the listener type
4646 */
47 public static <L> void addEventListener(Object eventSource, Class<L> listenerType, L listener) {
47 public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType, final L listener) {
4848 try {
4949 MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
50 } catch (NoSuchMethodException e) {
50 } catch (final NoSuchMethodException e) {
5151 throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
5252 + " does not have a public add" + listenerType.getSimpleName()
5353 + " method which takes a parameter of type " + listenerType.getName() + ".");
54 } catch (IllegalAccessException e) {
54 } catch (final IllegalAccessException e) {
5555 throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
5656 + " does not have an accessible add" + listenerType.getSimpleName ()
5757 + " method which takes a parameter of type " + listenerType.getName() + ".");
58 } catch (InvocationTargetException e) {
58 } catch (final InvocationTargetException e) {
5959 throw new RuntimeException("Unable to add listener.", e.getCause());
6060 }
6161 }
7171 * @param eventTypes the event types (method names) from the listener interface (if none specified, all will be
7272 * supported)
7373 */
74 public static <L> void bindEventsToMethod(Object target, String methodName, Object eventSource,
75 Class<L> listenerType, String... eventTypes) {
74 public static <L> void bindEventsToMethod(final Object target, final String methodName, final Object eventSource,
75 final Class<L> listenerType, final String... eventTypes) {
7676 final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(),
7777 new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes)));
7878 addEventListener(eventSource, listenerType, listener);
9090 * @param methodName the name of the method to be invoked
9191 * @param eventTypes the names of the supported event types
9292 */
93 EventBindingInvocationHandler(final Object target, final String methodName, String[] eventTypes) {
93 EventBindingInvocationHandler(final Object target, final String methodName, final String[] eventTypes) {
9494 this.target = target;
9595 this.methodName = methodName;
9696 this.eventTypes = new HashSet<String>(Arrays.asList(eventTypes));
105105 * @return the result of the method call
106106 * @throws Throwable if an error occurs
107107 */
108 @Override
108109 public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable {
109110 if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) {
110111 if (hasMatchingParametersMethod(method)) {
104104 *
105105 * @param message the exception message, may be null
106106 */
107 public ContextedException(String message) {
107 public ContextedException(final String message) {
108108 super(message);
109109 exceptionContext = new DefaultExceptionContext();
110110 }
116116 *
117117 * @param cause the underlying cause of the exception, may be null
118118 */
119 public ContextedException(Throwable cause) {
119 public ContextedException(final Throwable cause) {
120120 super(cause);
121121 exceptionContext = new DefaultExceptionContext();
122122 }
129129 * @param message the exception message, may be null
130130 * @param cause the underlying cause of the exception, may be null
131131 */
132 public ContextedException(String message, Throwable cause) {
132 public ContextedException(final String message, final Throwable cause) {
133133 super(message, cause);
134134 exceptionContext = new DefaultExceptionContext();
135135 }
141141 * @param cause the underlying cause of the exception, may be null
142142 * @param context the context used to store the additional information, null uses default implementation
143143 */
144 public ContextedException(String message, Throwable cause, ExceptionContext context) {
144 public ContextedException(final String message, final Throwable cause, ExceptionContext context) {
145145 super(message, cause);
146146 if (context == null) {
147147 context = new DefaultExceptionContext();
163163 * @param value information needed to understand exception, may be {@code null}
164164 * @return {@code this}, for method chaining, not {@code null}
165165 */
166 public ContextedException addContextValue(String label, Object value) {
166 @Override
167 public ContextedException addContextValue(final String label, final Object value) {
167168 exceptionContext.addContextValue(label, value);
168169 return this;
169170 }
181182 * @param value information needed to understand exception, may be {@code null}
182183 * @return {@code this}, for method chaining, not {@code null}
183184 */
184 public ContextedException setContextValue(String label, Object value) {
185 @Override
186 public ContextedException setContextValue(final String label, final Object value) {
185187 exceptionContext.setContextValue(label, value);
186188 return this;
187189 }
189191 /**
190192 * {@inheritDoc}
191193 */
192 public List<Object> getContextValues(String label) {
194 @Override
195 public List<Object> getContextValues(final String label) {
193196 return this.exceptionContext.getContextValues(label);
194197 }
195198
196199 /**
197200 * {@inheritDoc}
198201 */
199 public Object getFirstContextValue(String label) {
202 @Override
203 public Object getFirstContextValue(final String label) {
200204 return this.exceptionContext.getFirstContextValue(label);
201205 }
202206
203207 /**
204208 * {@inheritDoc}
205209 */
210 @Override
206211 public List<Pair<String, Object>> getContextEntries() {
207212 return this.exceptionContext.getContextEntries();
208213 }
210215 /**
211216 * {@inheritDoc}
212217 */
218 @Override
213219 public Set<String> getContextLabels() {
214220 return exceptionContext.getContextLabels();
215221 }
239245 /**
240246 * {@inheritDoc}
241247 */
242 public String getFormattedExceptionMessage(String baseMessage) {
248 @Override
249 public String getFormattedExceptionMessage(final String baseMessage) {
243250 return exceptionContext.getFormattedExceptionMessage(baseMessage);
244251 }
245252 }
104104 *
105105 * @param message the exception message, may be null
106106 */
107 public ContextedRuntimeException(String message) {
107 public ContextedRuntimeException(final String message) {
108108 super(message);
109109 exceptionContext = new DefaultExceptionContext();
110110 }
116116 *
117117 * @param cause the underlying cause of the exception, may be null
118118 */
119 public ContextedRuntimeException(Throwable cause) {
119 public ContextedRuntimeException(final Throwable cause) {
120120 super(cause);
121121 exceptionContext = new DefaultExceptionContext();
122122 }
129129 * @param message the exception message, may be null
130130 * @param cause the underlying cause of the exception, may be null
131131 */
132 public ContextedRuntimeException(String message, Throwable cause) {
132 public ContextedRuntimeException(final String message, final Throwable cause) {
133133 super(message, cause);
134134 exceptionContext = new DefaultExceptionContext();
135135 }
141141 * @param cause the underlying cause of the exception, may be null
142142 * @param context the context used to store the additional information, null uses default implementation
143143 */
144 public ContextedRuntimeException(String message, Throwable cause, ExceptionContext context) {
144 public ContextedRuntimeException(final String message, final Throwable cause, ExceptionContext context) {
145145 super(message, cause);
146146 if (context == null) {
147147 context = new DefaultExceptionContext();
163163 * @param value information needed to understand exception, may be {@code null}
164164 * @return {@code this}, for method chaining, not {@code null}
165165 */
166 public ContextedRuntimeException addContextValue(String label, Object value) {
166 @Override
167 public ContextedRuntimeException addContextValue(final String label, final Object value) {
167168 exceptionContext.addContextValue(label, value);
168169 return this;
169170 }
181182 * @param value information needed to understand exception, may be {@code null}
182183 * @return {@code this}, for method chaining, not {@code null}
183184 */
184 public ContextedRuntimeException setContextValue(String label, Object value) {
185 @Override
186 public ContextedRuntimeException setContextValue(final String label, final Object value) {
185187 exceptionContext.setContextValue(label, value);
186188 return this;
187189 }
189191 /**
190192 * {@inheritDoc}
191193 */
192 public List<Object> getContextValues(String label) {
194 @Override
195 public List<Object> getContextValues(final String label) {
193196 return this.exceptionContext.getContextValues(label);
194197 }
195198
196199 /**
197200 * {@inheritDoc}
198201 */
199 public Object getFirstContextValue(String label) {
202 @Override
203 public Object getFirstContextValue(final String label) {
200204 return this.exceptionContext.getFirstContextValue(label);
201205 }
202206
203207 /**
204208 * {@inheritDoc}
205209 */
210 @Override
206211 public List<Pair<String, Object>> getContextEntries() {
207212 return this.exceptionContext.getContextEntries();
208213 }
210215 /**
211216 * {@inheritDoc}
212217 */
218 @Override
213219 public Set<String> getContextLabels() {
214220 return exceptionContext.getContextLabels();
215221 }
239245 /**
240246 * {@inheritDoc}
241247 */
242 public String getFormattedExceptionMessage(String baseMessage) {
248 @Override
249 public String getFormattedExceptionMessage(final String baseMessage) {
243250 return exceptionContext.getFormattedExceptionMessage(baseMessage);
244251 }
245252
4848 /**
4949 * {@inheritDoc}
5050 */
51 public DefaultExceptionContext addContextValue(String label, Object value) {
51 @Override
52 public DefaultExceptionContext addContextValue(final String label, final Object value) {
5253 contextValues.add(new ImmutablePair<String, Object>(label, value));
5354 return this;
5455 }
5657 /**
5758 * {@inheritDoc}
5859 */
59 public DefaultExceptionContext setContextValue(String label, Object value) {
60 @Override
61 public DefaultExceptionContext setContextValue(final String label, final Object value) {
6062 for (final Iterator<Pair<String, Object>> iter = contextValues.iterator(); iter.hasNext();) {
6163 final Pair<String, Object> p = iter.next();
6264 if (StringUtils.equals(label, p.getKey())) {
7072 /**
7173 * {@inheritDoc}
7274 */
73 public List<Object> getContextValues(String label) {
75 @Override
76 public List<Object> getContextValues(final String label) {
7477 final List<Object> values = new ArrayList<Object>();
7578 for (final Pair<String, Object> pair : contextValues) {
7679 if (StringUtils.equals(label, pair.getKey())) {
8386 /**
8487 * {@inheritDoc}
8588 */
86 public Object getFirstContextValue(String label) {
89 @Override
90 public Object getFirstContextValue(final String label) {
8791 for (final Pair<String, Object> pair : contextValues) {
8892 if (StringUtils.equals(label, pair.getKey())) {
8993 return pair.getValue();
9599 /**
96100 * {@inheritDoc}
97101 */
102 @Override
98103 public Set<String> getContextLabels() {
99104 final Set<String> labels = new HashSet<String>();
100105 for (final Pair<String, Object> pair : contextValues) {
106111 /**
107112 * {@inheritDoc}
108113 */
114 @Override
109115 public List<Pair<String, Object>> getContextEntries() {
110116 return contextValues;
111117 }
116122 * @param baseMessage the base exception message <b>without</b> context information appended
117123 * @return the exception message <b>with</b> context information appended, never null
118124 */
119 public String getFormattedExceptionMessage(String baseMessage){
120 StringBuilder buffer = new StringBuilder(256);
125 @Override
126 public String getFormattedExceptionMessage(final String baseMessage){
127 final StringBuilder buffer = new StringBuilder(256);
121128 if (baseMessage != null) {
122129 buffer.append(baseMessage);
123130 }
142149 String valueStr;
143150 try {
144151 valueStr = value.toString();
145 } catch (Exception e) {
152 } catch (final Exception e) {
146153 valueStr = "Exception thrown on toString(): " + ExceptionUtils.getStackTrace(e);
147154 }
148155 buffer.append(valueStr);
4545 * @param value the value of item to add, may be {@code null}
4646 * @return {@code this}, for method chaining, not {@code null}
4747 */
48 public ExceptionContext addContextValue(String label, Object value);
48 ExceptionContext addContextValue(String label, Object value);
4949
5050 /**
5151 * Sets a contextual label-value pair into this context.
5858 * @param value the value of item to add, may be {@code null}
5959 * @return {@code this}, for method chaining, not {@code null}
6060 */
61 public ExceptionContext setContextValue(String label, Object value);
61 ExceptionContext setContextValue(String label, Object value);
6262
6363 /**
6464 * Retrieves all the contextual data values associated with the label.
6666 * @param label the label to get the contextual values for, may be {@code null}
6767 * @return the contextual values associated with the label, never {@code null}
6868 */
69 public List<Object> getContextValues(String label);
69 List<Object> getContextValues(String label);
7070
7171 /**
7272 * Retrieves the first available contextual data value associated with the label.
7474 * @param label the label to get the contextual value for, may be {@code null}
7575 * @return the first contextual value associated with the label, may be {@code null}
7676 */
77 public Object getFirstContextValue(String label);
77 Object getFirstContextValue(String label);
7878
7979 /**
8080 * Retrieves the full set of labels defined in the contextual data.
8181 *
8282 * @return the set of labels, not {@code null}
8383 */
84 public Set<String> getContextLabels();
84 Set<String> getContextLabels();
8585
8686 /**
8787 * Retrieves the full list of label-value pairs defined in the contextual data.
8888 *
8989 * @return the list of pairs, not {@code null}
9090 */
91 public List<Pair<String, Object>> getContextEntries();
91 List<Pair<String, Object>> getContextEntries();
9292
9393 /**
9494 * Gets the contextualized error message based on a base message.
9797 * @param baseMessage the base exception message <b>without</b> context information appended
9898 * @return the exception message <b>with</b> context information appended, not {@code null}
9999 */
100 public String getFormattedExceptionMessage(String baseMessage);
100 String getFormattedExceptionMessage(String baseMessage);
101101
102102 }
3434 * <code>Throwable</code> objects.</p>
3535 *
3636 * @since 1.0
37 * @version $Id: ExceptionUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
37 * @version $Id: ExceptionUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3838 */
3939 public class ExceptionUtils {
4040
119119 * @deprecated This feature will be removed in Lang 4.0
120120 */
121121 @Deprecated
122 public static Throwable getCause(Throwable throwable) {
122 public static Throwable getCause(final Throwable throwable) {
123123 return getCause(throwable, CAUSE_METHOD_NAMES);
124124 }
125125
137137 * @deprecated This feature will be removed in Lang 4.0
138138 */
139139 @Deprecated
140 public static Throwable getCause(Throwable throwable, String[] methodNames) {
140 public static Throwable getCause(final Throwable throwable, String[] methodNames) {
141141 if (throwable == null) {
142142 return null;
143143 }
146146 methodNames = CAUSE_METHOD_NAMES;
147147 }
148148
149 for (String methodName : methodNames) {
149 for (final String methodName : methodNames) {
150150 if (methodName != null) {
151 Throwable cause = getCauseUsingMethodName(throwable, methodName);
151 final Throwable cause = getCauseUsingMethodName(throwable, methodName);
152152 if (cause != null) {
153153 return cause;
154154 }
175175 * @return the root cause of the <code>Throwable</code>,
176176 * <code>null</code> if none found or null throwable input
177177 */
178 public static Throwable getRootCause(Throwable throwable) {
179 List<Throwable> list = getThrowableList(throwable);
178 public static Throwable getRootCause(final Throwable throwable) {
179 final List<Throwable> list = getThrowableList(throwable);
180180 return list.size() < 2 ? null : (Throwable)list.get(list.size() - 1);
181181 }
182182
188188 * @return the wrapped exception, or <code>null</code> if not found
189189 */
190190 // TODO: Remove in Lang 4.0
191 private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) {
191 private static Throwable getCauseUsingMethodName(final Throwable throwable, final String methodName) {
192192 Method method = null;
193193 try {
194194 method = throwable.getClass().getMethod(methodName);
195 } catch (NoSuchMethodException ignored) { // NOPMD
195 } catch (final NoSuchMethodException ignored) { // NOPMD
196196 // exception ignored
197 } catch (SecurityException ignored) { // NOPMD
197 } catch (final SecurityException ignored) { // NOPMD
198198 // exception ignored
199199 }
200200
201201 if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
202202 try {
203203 return (Throwable) method.invoke(throwable);
204 } catch (IllegalAccessException ignored) { // NOPMD
204 } catch (final IllegalAccessException ignored) { // NOPMD
205205 // exception ignored
206 } catch (IllegalArgumentException ignored) { // NOPMD
206 } catch (final IllegalArgumentException ignored) { // NOPMD
207207 // exception ignored
208 } catch (InvocationTargetException ignored) { // NOPMD
208 } catch (final InvocationTargetException ignored) { // NOPMD
209209 // exception ignored
210210 }
211211 }
229229 * @param throwable the throwable to inspect, may be null
230230 * @return the count of throwables, zero if null input
231231 */
232 public static int getThrowableCount(Throwable throwable) {
232 public static int getThrowableCount(final Throwable throwable) {
233233 return getThrowableList(throwable).size();
234234 }
235235
252252 * @param throwable the throwable to inspect, may be null
253253 * @return the array of throwables, never null
254254 */
255 public static Throwable[] getThrowables(Throwable throwable) {
256 List<Throwable> list = getThrowableList(throwable);
255 public static Throwable[] getThrowables(final Throwable throwable) {
256 final List<Throwable> list = getThrowableList(throwable);
257257 return list.toArray(new Throwable[list.size()]);
258258 }
259259
277277 * @since Commons Lang 2.2
278278 */
279279 public static List<Throwable> getThrowableList(Throwable throwable) {
280 List<Throwable> list = new ArrayList<Throwable>();
280 final List<Throwable> list = new ArrayList<Throwable>();
281281 while (throwable != null && list.contains(throwable) == false) {
282282 list.add(throwable);
283283 throwable = ExceptionUtils.getCause(throwable);
300300 * @param clazz the class to search for, subclasses do not match, null returns -1
301301 * @return the index into the throwable chain, -1 if no match or null input
302302 */
303 public static int indexOfThrowable(Throwable throwable, Class<?> clazz) {
303 public static int indexOfThrowable(final Throwable throwable, final Class<?> clazz) {
304304 return indexOf(throwable, clazz, 0, false);
305305 }
306306
323323 * negative treated as zero, larger than chain size returns -1
324324 * @return the index into the throwable chain, -1 if no match or null input
325325 */
326 public static int indexOfThrowable(Throwable throwable, Class<?> clazz, int fromIndex) {
326 public static int indexOfThrowable(final Throwable throwable, final Class<?> clazz, final int fromIndex) {
327327 return indexOf(throwable, clazz, fromIndex, false);
328328 }
329329
343343 * @return the index into the throwable chain, -1 if no match or null input
344344 * @since 2.1
345345 */
346 public static int indexOfType(Throwable throwable, Class<?> type) {
346 public static int indexOfType(final Throwable throwable, final Class<?> type) {
347347 return indexOf(throwable, type, 0, true);
348348 }
349349
367367 * @return the index into the throwable chain, -1 if no match or null input
368368 * @since 2.1
369369 */
370 public static int indexOfType(Throwable throwable, Class<?> type, int fromIndex) {
370 public static int indexOfType(final Throwable throwable, final Class<?> type, final int fromIndex) {
371371 return indexOf(throwable, type, fromIndex, true);
372372 }
373373
380380 * negative treated as zero, larger than chain size returns -1
381381 * @param subclass if <code>true</code>, compares with {@link Class#isAssignableFrom(Class)}, otherwise compares
382382 * using references
383 * @return index of the <code>type</code> within throwables nested withing the specified <code>throwable</code>
384 */
385 private static int indexOf(Throwable throwable, Class<?> type, int fromIndex, boolean subclass) {
383 * @return index of the <code>type</code> within throwables nested within the specified <code>throwable</code>
384 */
385 private static int indexOf(final Throwable throwable, final Class<?> type, int fromIndex, final boolean subclass) {
386386 if (throwable == null || type == null) {
387387 return -1;
388388 }
389389 if (fromIndex < 0) {
390390 fromIndex = 0;
391391 }
392 Throwable[] throwables = ExceptionUtils.getThrowables(throwable);
392 final Throwable[] throwables = ExceptionUtils.getThrowables(throwable);
393393 if (fromIndex >= throwables.length) {
394394 return -1;
395395 }
428428 * @param throwable the throwable to output
429429 * @since 2.0
430430 */
431 public static void printRootCauseStackTrace(Throwable throwable) {
431 public static void printRootCauseStackTrace(final Throwable throwable) {
432432 printRootCauseStackTrace(throwable, System.err);
433433 }
434434
451451 * @throws IllegalArgumentException if the stream is <code>null</code>
452452 * @since 2.0
453453 */
454 public static void printRootCauseStackTrace(Throwable throwable, PrintStream stream) {
454 public static void printRootCauseStackTrace(final Throwable throwable, final PrintStream stream) {
455455 if (throwable == null) {
456456 return;
457457 }
458458 if (stream == null) {
459459 throw new IllegalArgumentException("The PrintStream must not be null");
460460 }
461 String trace[] = getRootCauseStackTrace(throwable);
462 for (String element : trace) {
461 final String trace[] = getRootCauseStackTrace(throwable);
462 for (final String element : trace) {
463463 stream.println(element);
464464 }
465465 stream.flush();
484484 * @throws IllegalArgumentException if the writer is <code>null</code>
485485 * @since 2.0
486486 */
487 public static void printRootCauseStackTrace(Throwable throwable, PrintWriter writer) {
487 public static void printRootCauseStackTrace(final Throwable throwable, final PrintWriter writer) {
488488 if (throwable == null) {
489489 return;
490490 }
491491 if (writer == null) {
492492 throw new IllegalArgumentException("The PrintWriter must not be null");
493493 }
494 String trace[] = getRootCauseStackTrace(throwable);
495 for (String element : trace) {
494 final String trace[] = getRootCauseStackTrace(throwable);
495 for (final String element : trace) {
496496 writer.println(element);
497497 }
498498 writer.flush();
512512 * @return an array of stack trace frames, never null
513513 * @since 2.0
514514 */
515 public static String[] getRootCauseStackTrace(Throwable throwable) {
515 public static String[] getRootCauseStackTrace(final Throwable throwable) {
516516 if (throwable == null) {
517517 return ArrayUtils.EMPTY_STRING_ARRAY;
518518 }
519 Throwable throwables[] = getThrowables(throwable);
520 int count = throwables.length;
521 List<String> frames = new ArrayList<String>();
519 final Throwable throwables[] = getThrowables(throwable);
520 final int count = throwables.length;
521 final List<String> frames = new ArrayList<String>();
522522 List<String> nextTrace = getStackFrameList(throwables[count - 1]);
523523 for (int i = count; --i >= 0;) {
524 List<String> trace = nextTrace;
524 final List<String> trace = nextTrace;
525525 if (i != 0) {
526526 nextTrace = getStackFrameList(throwables[i - 1]);
527527 removeCommonFrames(trace, nextTrace);
546546 * @throws IllegalArgumentException if either argument is null
547547 * @since 2.0
548548 */
549 public static void removeCommonFrames(List<String> causeFrames, List<String> wrapperFrames) {
549 public static void removeCommonFrames(final List<String> causeFrames, final List<String> wrapperFrames) {
550550 if (causeFrames == null || wrapperFrames == null) {
551551 throw new IllegalArgumentException("The List must not be null");
552552 }
555555 while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) {
556556 // Remove the frame from the cause trace if it is the same
557557 // as in the wrapper trace
558 String causeFrame = causeFrames.get(causeFrameIndex);
559 String wrapperFrame = wrapperFrames.get(wrapperFrameIndex);
558 final String causeFrame = causeFrames.get(causeFrameIndex);
559 final String wrapperFrame = wrapperFrames.get(wrapperFrameIndex);
560560 if (causeFrame.equals(wrapperFrame)) {
561561 causeFrames.remove(causeFrameIndex);
562562 }
578578 * @return the stack trace as generated by the exception's
579579 * <code>printStackTrace(PrintWriter)</code> method
580580 */
581 public static String getStackTrace(Throwable throwable) {
582 StringWriter sw = new StringWriter();
583 PrintWriter pw = new PrintWriter(sw, true);
581 public static String getStackTrace(final Throwable throwable) {
582 final StringWriter sw = new StringWriter();
583 final PrintWriter pw = new PrintWriter(sw, true);
584584 throwable.printStackTrace(pw);
585585 return sw.getBuffer().toString();
586586 }
598598 * @param throwable the <code>Throwable</code> to examine, may be null
599599 * @return an array of strings describing each stack frame, never null
600600 */
601 public static String[] getStackFrames(Throwable throwable) {
601 public static String[] getStackFrames(final Throwable throwable) {
602602 if (throwable == null) {
603603 return ArrayUtils.EMPTY_STRING_ARRAY;
604604 }
614614 * @param stackTrace a stack trace String
615615 * @return an array where each element is a line from the argument
616616 */
617 static String[] getStackFrames(String stackTrace) {
618 String linebreak = SystemUtils.LINE_SEPARATOR;
619 StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
620 List<String> list = new ArrayList<String>();
617 static String[] getStackFrames(final String stackTrace) {
618 final String linebreak = SystemUtils.LINE_SEPARATOR;
619 final StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
620 final List<String> list = new ArrayList<String>();
621621 while (frames.hasMoreTokens()) {
622622 list.add(frames.nextToken());
623623 }
636636 * @param t is any throwable
637637 * @return List of stack frames
638638 */
639 static List<String> getStackFrameList(Throwable t) {
640 String stackTrace = getStackTrace(t);
641 String linebreak = SystemUtils.LINE_SEPARATOR;
642 StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
643 List<String> list = new ArrayList<String>();
639 static List<String> getStackFrameList(final Throwable t) {
640 final String stackTrace = getStackTrace(t);
641 final String linebreak = SystemUtils.LINE_SEPARATOR;
642 final StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
643 final List<String> list = new ArrayList<String>();
644644 boolean traceStarted = false;
645645 while (frames.hasMoreTokens()) {
646 String token = frames.nextToken();
646 final String token = frames.nextToken();
647647 // Determine if the line starts with <whitespace>at
648 int at = token.indexOf("at");
649 if (at != -1 && token.substring(0, at).trim().length() == 0) {
648 final int at = token.indexOf("at");
649 if (at != -1 && token.substring(0, at).trim().isEmpty()) {
650650 traceStarted = true;
651651 list.add(token);
652652 } else if (traceStarted) {
667667 * @return the message, non-null
668668 * @since Commons Lang 2.2
669669 */
670 public static String getMessage(Throwable th) {
670 public static String getMessage(final Throwable th) {
671671 if (th == null) {
672672 return "";
673673 }
674 String clsName = ClassUtils.getShortClassName(th, null);
675 String msg = th.getMessage();
674 final String clsName = ClassUtils.getShortClassName(th, null);
675 final String msg = th.getMessage();
676676 return clsName + ": " + StringUtils.defaultString(msg);
677677 }
678678
687687 * @return the message, non-null
688688 * @since Commons Lang 2.2
689689 */
690 public static String getRootCauseMessage(Throwable th) {
690 public static String getRootCauseMessage(final Throwable th) {
691691 Throwable root = ExceptionUtils.getRootCause(th);
692692 root = root == null ? th : root;
693693 return getMessage(root);
2929 * equivalent, please see the Commons Math BigFraction class. </p>
3030 *
3131 * @since 2.0
32 * @version $Id: Fraction.java 1199894 2011-11-09 17:53:59Z ggregory $
32 * @version $Id: Fraction.java 1436770 2013-01-22 07:09:45Z ggregory $
3333 */
3434 public final class Fraction extends Number implements Comparable<Fraction> {
3535
119119 * @param numerator the numerator, for example the three in 'three sevenths'
120120 * @param denominator the denominator, for example the seven in 'three sevenths'
121121 */
122 private Fraction(int numerator, int denominator) {
122 private Fraction(final int numerator, final int denominator) {
123123 super();
124124 this.numerator = numerator;
125125 this.denominator = denominator;
168168 * @throws ArithmeticException if the resulting numerator exceeds
169169 * <code>Integer.MAX_VALUE</code>
170170 */
171 public static Fraction getFraction(int whole, int numerator, int denominator) {
171 public static Fraction getFraction(final int whole, final int numerator, final int denominator) {
172172 if (denominator == 0) {
173173 throw new ArithmeticException("The denominator must not be zero");
174174 }
225225 denominator = -denominator;
226226 }
227227 // simplify fraction.
228 int gcd = greatestCommonDivisor(numerator, denominator);
228 final int gcd = greatestCommonDivisor(numerator, denominator);
229229 numerator /= gcd;
230230 denominator /= gcd;
231231 return new Fraction(numerator, denominator);
246246 * @throws ArithmeticException if the the algorithm does not converge
247247 */
248248 public static Fraction getFraction(double value) {
249 int sign = value < 0 ? -1 : 1;
249 final int sign = value < 0 ? -1 : 1;
250250 value = Math.abs(value);
251251 if (value > Integer.MAX_VALUE || Double.isNaN(value)) {
252252 throw new ArithmeticException
253253 ("The value must not be greater than Integer.MAX_VALUE or NaN");
254254 }
255 int wholeNumber = (int) value;
255 final int wholeNumber = (int) value;
256256 value -= wholeNumber;
257257
258258 int numer0 = 0; // the pre-previous
328328 // parse X Y/Z format
329329 pos = str.indexOf(' ');
330330 if (pos > 0) {
331 int whole = Integer.parseInt(str.substring(0, pos));
331 final int whole = Integer.parseInt(str.substring(0, pos));
332332 str = str.substring(pos + 1);
333333 pos = str.indexOf('/');
334334 if (pos < 0) {
335335 throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z");
336336 } else {
337 int numer = Integer.parseInt(str.substring(0, pos));
338 int denom = Integer.parseInt(str.substring(pos + 1));
337 final int numer = Integer.parseInt(str.substring(0, pos));
338 final int denom = Integer.parseInt(str.substring(pos + 1));
339339 return getFraction(whole, numer, denom);
340340 }
341341 }
346346 // simple whole number
347347 return getFraction(Integer.parseInt(str), 1);
348348 } else {
349 int numer = Integer.parseInt(str.substring(0, pos));
350 int denom = Integer.parseInt(str.substring(pos + 1));
349 final int numer = Integer.parseInt(str.substring(0, pos));
350 final int denom = Integer.parseInt(str.substring(pos + 1));
351351 return getFraction(numer, denom);
352352 }
353353 }
469469 if (numerator == 0) {
470470 return equals(ZERO) ? this : ZERO;
471471 }
472 int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
472 final int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
473473 if (gcd == 1) {
474474 return this;
475475 }
542542 * @throws ArithmeticException if the resulting numerator or denominator exceeds
543543 * <code>Integer.MAX_VALUE</code>
544544 */
545 public Fraction pow(int power) {
545 public Fraction pow(final int power) {
546546 if (power == 1) {
547547 return this;
548548 } else if (power == 0) {
553553 }
554554 return this.invert().pow(-power);
555555 } else {
556 Fraction f = this.multiplyBy(this);
556 final Fraction f = this.multiplyBy(this);
557557 if (power % 2 == 0) { // if even...
558558 return f.pow(power/2);
559559 } else { // if odd...
635635 * @throws ArithmeticException if the result can not be represented as
636636 * an int
637637 */
638 private static int mulAndCheck(int x, int y) {
639 long m = (long)x*(long)y;
638 private static int mulAndCheck(final int x, final int y) {
639 final long m = (long)x*(long)y;
640640 if (m < Integer.MIN_VALUE ||
641641 m > Integer.MAX_VALUE) {
642642 throw new ArithmeticException("overflow: mul");
653653 * @throws ArithmeticException if the result can not be represented as
654654 * an int
655655 */
656 private static int mulPosAndCheck(int x, int y) {
656 private static int mulPosAndCheck(final int x, final int y) {
657657 /* assert x>=0 && y>=0; */
658 long m = (long)x*(long)y;
658 final long m = (long)x*(long)y;
659659 if (m > Integer.MAX_VALUE) {
660660 throw new ArithmeticException("overflow: mulPos");
661661 }
671671 * @throws ArithmeticException if the result can not be represented as
672672 * an int
673673 */
674 private static int addAndCheck(int x, int y) {
675 long s = (long)x+(long)y;
674 private static int addAndCheck(final int x, final int y) {
675 final long s = (long)x+(long)y;
676676 if (s < Integer.MIN_VALUE ||
677677 s > Integer.MAX_VALUE) {
678678 throw new ArithmeticException("overflow: add");
689689 * @throws ArithmeticException if the result can not be represented as
690690 * an int
691691 */
692 private static int subAndCheck(int x, int y) {
693 long s = (long)x-(long)y;
692 private static int subAndCheck(final int x, final int y) {
693 final long s = (long)x-(long)y;
694694 if (s < Integer.MIN_VALUE ||
695695 s > Integer.MAX_VALUE) {
696696 throw new ArithmeticException("overflow: add");
708708 * @throws ArithmeticException if the resulting numerator or denominator exceeds
709709 * <code>Integer.MAX_VALUE</code>
710710 */
711 public Fraction add(Fraction fraction) {
711 public Fraction add(final Fraction fraction) {
712712 return addSub(fraction, true /* add */);
713713 }
714714
722722 * @throws ArithmeticException if the resulting numerator or denominator
723723 * cannot be represented in an <code>int</code>.
724724 */
725 public Fraction subtract(Fraction fraction) {
725 public Fraction subtract(final Fraction fraction) {
726726 return addSub(fraction, false /* subtract */);
727727 }
728728
736736 * @throws ArithmeticException if the resulting numerator or denominator
737737 * cannot be represented in an <code>int</code>.
738738 */
739 private Fraction addSub(Fraction fraction, boolean isAdd) {
739 private Fraction addSub(final Fraction fraction, final boolean isAdd) {
740740 if (fraction == null) {
741741 throw new IllegalArgumentException("The fraction must not be null");
742742 }
749749 }
750750 // if denominators are randomly distributed, d1 will be 1 about 61%
751751 // of the time.
752 int d1 = greatestCommonDivisor(denominator, fraction.denominator);
752 final int d1 = greatestCommonDivisor(denominator, fraction.denominator);
753753 if (d1==1) {
754754 // result is ( (u*v' +/- u'v) / u'v')
755 int uvp = mulAndCheck(numerator, fraction.denominator);
756 int upv = mulAndCheck(fraction.numerator, denominator);
755 final int uvp = mulAndCheck(numerator, fraction.denominator);
756 final int upv = mulAndCheck(fraction.numerator, denominator);
757757 return new Fraction
758758 (isAdd ? addAndCheck(uvp, upv) : subAndCheck(uvp, upv),
759759 mulPosAndCheck(denominator, fraction.denominator));
761761 // the quantity 't' requires 65 bits of precision; see knuth 4.5.1
762762 // exercise 7. we're going to use a BigInteger.
763763 // t = u(v'/d1) +/- v(u'/d1)
764 BigInteger uvp = BigInteger.valueOf(numerator)
764 final BigInteger uvp = BigInteger.valueOf(numerator)
765765 .multiply(BigInteger.valueOf(fraction.denominator/d1));
766 BigInteger upv = BigInteger.valueOf(fraction.numerator)
766 final BigInteger upv = BigInteger.valueOf(fraction.numerator)
767767 .multiply(BigInteger.valueOf(denominator/d1));
768 BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv);
768 final BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv);
769769 // but d2 doesn't need extra precision because
770770 // d2 = gcd(t,d1) = gcd(t mod d1, d1)
771 int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue();
772 int d2 = tmodd1==0?d1:greatestCommonDivisor(tmodd1, d1);
771 final int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue();
772 final int d2 = tmodd1==0?d1:greatestCommonDivisor(tmodd1, d1);
773773
774774 // result is (t/d2) / (u'/d1)(v'/d2)
775 BigInteger w = t.divide(BigInteger.valueOf(d2));
775 final BigInteger w = t.divide(BigInteger.valueOf(d2));
776776 if (w.bitLength() > 31) {
777777 throw new ArithmeticException
778778 ("overflow: numerator too large after multiply");
792792 * @throws ArithmeticException if the resulting numerator or denominator exceeds
793793 * <code>Integer.MAX_VALUE</code>
794794 */
795 public Fraction multiplyBy(Fraction fraction) {
795 public Fraction multiplyBy(final Fraction fraction) {
796796 if (fraction == null) {
797797 throw new IllegalArgumentException("The fraction must not be null");
798798 }
801801 }
802802 // knuth 4.5.1
803803 // make sure we don't overflow unless the result *must* overflow.
804 int d1 = greatestCommonDivisor(numerator, fraction.denominator);
805 int d2 = greatestCommonDivisor(fraction.numerator, denominator);
804 final int d1 = greatestCommonDivisor(numerator, fraction.denominator);
805 final int d2 = greatestCommonDivisor(fraction.numerator, denominator);
806806 return getReducedFraction
807807 (mulAndCheck(numerator/d1, fraction.numerator/d2),
808808 mulPosAndCheck(denominator/d2, fraction.denominator/d1));
818818 * @throws ArithmeticException if the resulting numerator or denominator exceeds
819819 * <code>Integer.MAX_VALUE</code>
820820 */
821 public Fraction divideBy(Fraction fraction) {
821 public Fraction divideBy(final Fraction fraction) {
822822 if (fraction == null) {
823823 throw new IllegalArgumentException("The fraction must not be null");
824824 }
840840 * @return <code>true</code> if this object is equal
841841 */
842842 @Override
843 public boolean equals(Object obj) {
843 public boolean equals(final Object obj) {
844844 if (obj == this) {
845845 return true;
846846 }
847847 if (obj instanceof Fraction == false) {
848848 return false;
849849 }
850 Fraction other = (Fraction) obj;
850 final Fraction other = (Fraction) obj;
851851 return getNumerator() == other.getNumerator() &&
852852 getDenominator() == other.getDenominator();
853853 }
878878 * @throws ClassCastException if the object is not a <code>Fraction</code>
879879 * @throws NullPointerException if the object is <code>null</code>
880880 */
881 public int compareTo(Fraction other) {
881 @Override
882 public int compareTo(final Fraction other) {
882883 if (this==other) {
883884 return 0;
884885 }
887888 }
888889
889890 // otherwise see which is less
890 long first = (long) numerator * (long) other.denominator;
891 long second = (long) other.numerator * (long) denominator;
891 final long first = (long) numerator * (long) other.denominator;
892 final long second = (long) other.numerator * (long) denominator;
892893 if (first == second) {
893894 return 0;
894895 } else if (first < second) {
920921 * <p>Gets the fraction as a proper <code>String</code> in the format X Y/Z.</p>
921922 *
922923 * <p>The format used in '<i>wholeNumber</i> <i>numerator</i>/<i>denominator</i>'.
923 * If the whole number is zero it will be ommitted. If the numerator is zero,
924 * If the whole number is zero it will be omitted. If the numerator is zero,
924925 * only the whole number is returned.</p>
925926 *
926927 * @return a <code>String</code> form of the fraction
938939 // NEGATIVE (not positive) numbers, since negative numbers
939940 // have a larger range. otherwise numerator==Integer.MIN_VALUE
940941 // is handled incorrectly.
941 int properNumerator = getProperNumerator();
942 final int properNumerator = getProperNumerator();
942943 if (properNumerator == 0) {
943944 toProperString = Integer.toString(getProperWhole());
944945 } else {
2121 * <p>See: <a href="http://en.wikipedia.org/wiki/IEEE_754r">http://en.wikipedia.org/wiki/IEEE_754r</a></p>
2222 *
2323 * @since 2.4
24 * @version $Id: IEEE754rUtils.java 1088899 2011-04-05 05:31:27Z bayard $
24 * @version $Id: IEEE754rUtils.java 1436768 2013-01-22 07:07:42Z ggregory $
2525 */
2626 public class IEEE754rUtils {
2727
3333 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
3434 * @throws IllegalArgumentException if <code>array</code> is empty
3535 */
36 public static double min(double[] array) {
36 public static double min(final double[] array) {
3737 // Validates input
3838 if (array == null) {
3939 throw new IllegalArgumentException("The Array must not be null");
5858 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
5959 * @throws IllegalArgumentException if <code>array</code> is empty
6060 */
61 public static float min(float[] array) {
61 public static float min(final float[] array) {
6262 // Validates input
6363 if (array == null) {
6464 throw new IllegalArgumentException("The Array must not be null");
8585 * @param c value 3
8686 * @return the smallest of the values
8787 */
88 public static double min(double a, double b, double c) {
88 public static double min(final double a, final double b, final double c) {
8989 return min(min(a, b), c);
9090 }
9191
9898 * @param b value 2
9999 * @return the smallest of the values
100100 */
101 public static double min(double a, double b) {
101 public static double min(final double a, final double b) {
102102 if(Double.isNaN(a)) {
103103 return b;
104104 } else
119119 * @param c value 3
120120 * @return the smallest of the values
121121 */
122 public static float min(float a, float b, float c) {
122 public static float min(final float a, final float b, final float c) {
123123 return min(min(a, b), c);
124124 }
125125
132132 * @param b value 2
133133 * @return the smallest of the values
134134 */
135 public static float min(float a, float b) {
135 public static float min(final float a, final float b) {
136136 if(Float.isNaN(a)) {
137137 return b;
138138 } else
151151 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
152152 * @throws IllegalArgumentException if <code>array</code> is empty
153153 */
154 public static double max(double[] array) {
154 public static double max(final double[] array) {
155155 // Validates input
156156 if (array== null) {
157157 throw new IllegalArgumentException("The Array must not be null");
176176 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
177177 * @throws IllegalArgumentException if <code>array</code> is empty
178178 */
179 public static float max(float[] array) {
179 public static float max(final float[] array) {
180180 // Validates input
181181 if (array == null) {
182182 throw new IllegalArgumentException("The Array must not be null");
203203 * @param c value 3
204204 * @return the largest of the values
205205 */
206 public static double max(double a, double b, double c) {
206 public static double max(final double a, final double b, final double c) {
207207 return max(max(a, b), c);
208208 }
209209
216216 * @param b value 2
217217 * @return the largest of the values
218218 */
219 public static double max(double a, double b) {
219 public static double max(final double a, final double b) {
220220 if(Double.isNaN(a)) {
221221 return b;
222222 } else
237237 * @param c value 3
238238 * @return the largest of the values
239239 */
240 public static float max(float a, float b, float c) {
240 public static float max(final float a, final float b, final float c) {
241241 return max(max(a, b), c);
242242 }
243243
250250 * @param b value 2
251251 * @return the largest of the values
252252 */
253 public static float max(float a, float b) {
253 public static float max(final float a, final float b) {
254254 if(Float.isNaN(a)) {
255255 return b;
256256 } else
1515 */
1616 package org.apache.commons.lang3.math;
1717
18 import java.lang.reflect.Array;
1819 import java.math.BigDecimal;
1920 import java.math.BigInteger;
2021
2425 * <p>Provides extra functionality for Java Number classes.</p>
2526 *
2627 * @since 2.0
27 * @version $Id: NumberUtils.java 1199816 2011-11-09 16:11:34Z bayard $
28 * @version $Id: NumberUtils.java 1507169 2013-07-26 01:03:52Z sebb $
2829 */
2930 public class NumberUtils {
3031
9495 * conversion fails
9596 * @since 2.1
9697 */
97 public static int toInt(String str) {
98 public static int toInt(final String str) {
9899 return toInt(str, 0);
99100 }
100101
115116 * @return the int represented by the string, or the default if conversion fails
116117 * @since 2.1
117118 */
118 public static int toInt(String str, int defaultValue) {
119 public static int toInt(final String str, final int defaultValue) {
119120 if(str == null) {
120121 return defaultValue;
121122 }
122123 try {
123124 return Integer.parseInt(str);
124 } catch (NumberFormatException nfe) {
125 } catch (final NumberFormatException nfe) {
125126 return defaultValue;
126127 }
127128 }
143144 * conversion fails
144145 * @since 2.1
145146 */
146 public static long toLong(String str) {
147 public static long toLong(final String str) {
147148 return toLong(str, 0L);
148149 }
149150
164165 * @return the long represented by the string, or the default if conversion fails
165166 * @since 2.1
166167 */
167 public static long toLong(String str, long defaultValue) {
168 public static long toLong(final String str, final long defaultValue) {
168169 if (str == null) {
169170 return defaultValue;
170171 }
171172 try {
172173 return Long.parseLong(str);
173 } catch (NumberFormatException nfe) {
174 } catch (final NumberFormatException nfe) {
174175 return defaultValue;
175176 }
176177 }
193194 * if conversion fails
194195 * @since 2.1
195196 */
196 public static float toFloat(String str) {
197 public static float toFloat(final String str) {
197198 return toFloat(str, 0.0f);
198199 }
199200
216217 * if conversion fails
217218 * @since 2.1
218219 */
219 public static float toFloat(String str, float defaultValue) {
220 public static float toFloat(final String str, final float defaultValue) {
220221 if (str == null) {
221222 return defaultValue;
222223 }
223224 try {
224225 return Float.parseFloat(str);
225 } catch (NumberFormatException nfe) {
226 } catch (final NumberFormatException nfe) {
226227 return defaultValue;
227228 }
228229 }
245246 * if conversion fails
246247 * @since 2.1
247248 */
248 public static double toDouble(String str) {
249 public static double toDouble(final String str) {
249250 return toDouble(str, 0.0d);
250251 }
251252
268269 * if conversion fails
269270 * @since 2.1
270271 */
271 public static double toDouble(String str, double defaultValue) {
272 public static double toDouble(final String str, final double defaultValue) {
272273 if (str == null) {
273274 return defaultValue;
274275 }
275276 try {
276277 return Double.parseDouble(str);
277 } catch (NumberFormatException nfe) {
278 } catch (final NumberFormatException nfe) {
278279 return defaultValue;
279280 }
280281 }
297298 * conversion fails
298299 * @since 2.5
299300 */
300 public static byte toByte(String str) {
301 public static byte toByte(final String str) {
301302 return toByte(str, (byte) 0);
302303 }
303304
318319 * @return the byte represented by the string, or the default if conversion fails
319320 * @since 2.5
320321 */
321 public static byte toByte(String str, byte defaultValue) {
322 public static byte toByte(final String str, final byte defaultValue) {
322323 if(str == null) {
323324 return defaultValue;
324325 }
325326 try {
326327 return Byte.parseByte(str);
327 } catch (NumberFormatException nfe) {
328 } catch (final NumberFormatException nfe) {
328329 return defaultValue;
329330 }
330331 }
346347 * conversion fails
347348 * @since 2.5
348349 */
349 public static short toShort(String str) {
350 public static short toShort(final String str) {
350351 return toShort(str, (short) 0);
351352 }
352353
367368 * @return the short represented by the string, or the default if conversion fails
368369 * @since 2.5
369370 */
370 public static short toShort(String str, short defaultValue) {
371 public static short toShort(final String str, final short defaultValue) {
371372 if(str == null) {
372373 return defaultValue;
373374 }
374375 try {
375376 return Short.parseShort(str);
376 } catch (NumberFormatException nfe) {
377 } catch (final NumberFormatException nfe) {
377378 return defaultValue;
378379 }
379380 }
417418 /**
418419 * <p>Turns a string value into a java.lang.Number.</p>
419420 *
420 * <p>First, the value is examined for a type qualifier on the end
421 * (<code>'f','F','d','D','l','L'</code>). If it is found, it starts
421 * <p>If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it
422 * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the
423 * prefix is more than 8 - or BigInteger if there are more than 16 digits.
424 * </p>
425 * <p>Then, the value is examined for a type qualifier on the end, i.e. one of
426 * <code>'f','F','d','D','l','L'</code>. If it is found, it starts
422427 * trying to create successively larger types from the type specified
423428 * until one is found that can represent the value.</p>
424429 *
425430 * <p>If a type specifier is not found, it will check for a decimal point
426431 * and then try successively larger types from <code>Integer</code> to
427432 * <code>BigInteger</code> and from <code>Float</code> to
428 * <code>BigDecimal</code>.</p>
429 *
430 * <p>If the string starts with <code>0x</code> or <code>-0x</code> (lower or upper case), it
431 * will be interpreted as a hexadecimal integer. Values with leading
432 * <code>0</code>'s will not be interpreted as octal.</p>
433 * <code>BigDecimal</code>.</p>
434 *
435 * <p>
436 * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will
437 * be Integer, Long or BigDecimal as appropriate.
438 * </p>
433439 *
434440 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
435441 *
440446 * @return Number created from the string (or null if the input is null)
441447 * @throws NumberFormatException if the value cannot be converted
442448 */
443 public static Number createNumber(String str) throws NumberFormatException {
449 public static Number createNumber(final String str) throws NumberFormatException {
444450 if (str == null) {
445451 return null;
446452 }
447453 if (StringUtils.isBlank(str)) {
448454 throw new NumberFormatException("A blank string is not a valid number");
449 }
450 if (str.startsWith("--")) {
451 // this is protection for poorness in java.lang.BigDecimal.
452 // it accepts this as a legal value, but it does not appear
453 // to be in specification of class. OS X Java parses it to
454 // a wrong value.
455 return null;
456 }
457 if (str.startsWith("0x") || str.startsWith("-0x") || str.startsWith("0X") || str.startsWith("-0X")) {
455 }
456 // Need to deal with all possible hex prefixes here
457 final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"};
458 int pfxLen = 0;
459 for(final String pfx : hex_prefixes) {
460 if (str.startsWith(pfx)) {
461 pfxLen += pfx.length();
462 break;
463 }
464 }
465 if (pfxLen > 0) { // we have a hex number
466 char firstSigDigit = 0; // strip leading zeroes
467 for(int i = pfxLen; i < str.length(); i++) {
468 firstSigDigit = str.charAt(i);
469 if (firstSigDigit == '0') { // count leading zeroes
470 pfxLen++;
471 } else {
472 break;
473 }
474 }
475 final int hexDigits = str.length() - pfxLen;
476 if (hexDigits > 16 || (hexDigits == 16 && firstSigDigit > '7')) { // too many for Long
477 return createBigInteger(str);
478 }
479 if (hexDigits > 8 || (hexDigits == 8 && firstSigDigit > '7')) { // too many for an int
480 return createLong(str);
481 }
458482 return createInteger(str);
459 }
460 char lastChar = str.charAt(str.length() - 1);
483 }
484 final char lastChar = str.charAt(str.length() - 1);
461485 String mant;
462486 String dec;
463487 String exp;
464 int decPos = str.indexOf('.');
465 int expPos = str.indexOf('e') + str.indexOf('E') + 1;
466
467 if (decPos > -1) {
468
469 if (expPos > -1) {
470 if (expPos < decPos || expPos > str.length()) {
488 final int decPos = str.indexOf('.');
489 final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present
490 // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE)
491 // and the parsing which will detect if e or E appear in a number due to using the wrong offset
492
493 int numDecimals = 0; // Check required precision (LANG-693)
494 if (decPos > -1) { // there is a decimal point
495
496 if (expPos > -1) { // there is an exponent
497 if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE
471498 throw new NumberFormatException(str + " is not a valid number.");
472499 }
473500 dec = str.substring(decPos + 1, expPos);
475502 dec = str.substring(decPos + 1);
476503 }
477504 mant = str.substring(0, decPos);
505 numDecimals = dec.length(); // gets number of digits past the decimal to ensure no loss of precision for floating point numbers.
478506 } else {
479507 if (expPos > -1) {
480 if (expPos > str.length()) {
508 if (expPos > str.length()) { // prevents double exponent causing IOOBE
481509 throw new NumberFormatException(str + " is not a valid number.");
482510 }
483511 mant = str.substring(0, expPos);
493521 exp = null;
494522 }
495523 //Requesting a specific type..
496 String numeric = str.substring(0, str.length() - 1);
497 boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
524 final String numeric = str.substring(0, str.length() - 1);
525 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
498526 switch (lastChar) {
499527 case 'l' :
500528 case 'L' :
503531 && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
504532 try {
505533 return createLong(numeric);
506 } catch (NumberFormatException nfe) { // NOPMD
534 } catch (final NumberFormatException nfe) { // NOPMD
507535 // Too big for a long
508536 }
509537 return createBigInteger(numeric);
513541 case 'f' :
514542 case 'F' :
515543 try {
516 Float f = NumberUtils.createFloat(numeric);
544 final Float f = NumberUtils.createFloat(numeric);
517545 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
518546 //If it's too big for a float or the float value = 0 and the string
519547 //has non-zeros in it, then float does not have the precision we want
520548 return f;
521549 }
522550
523 } catch (NumberFormatException nfe) { // NOPMD
551 } catch (final NumberFormatException nfe) { // NOPMD
524552 // ignore the bad number
525553 }
526554 //$FALL-THROUGH$
527555 case 'd' :
528556 case 'D' :
529557 try {
530 Double d = NumberUtils.createDouble(numeric);
558 final Double d = NumberUtils.createDouble(numeric);
531559 if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
532560 return d;
533561 }
534 } catch (NumberFormatException nfe) { // NOPMD
562 } catch (final NumberFormatException nfe) { // NOPMD
535563 // ignore the bad number
536564 }
537565 try {
538566 return createBigDecimal(numeric);
539 } catch (NumberFormatException e) { // NOPMD
567 } catch (final NumberFormatException e) { // NOPMD
540568 // ignore the bad number
541569 }
542570 //$FALL-THROUGH$
544572 throw new NumberFormatException(str + " is not a valid number.");
545573
546574 }
575 }
576 //User doesn't have a preference on the return type, so let's start
577 //small and go from there...
578 if (expPos > -1 && expPos < str.length() - 1) {
579 exp = str.substring(expPos + 1, str.length());
547580 } else {
548 //User doesn't have a preference on the return type, so let's start
549 //small and go from there...
550 if (expPos > -1 && expPos < str.length() - 1) {
551 exp = str.substring(expPos + 1, str.length());
552 } else {
553 exp = null;
554 }
555 if (dec == null && exp == null) {
556 //Must be an int,long,bigint
557 try {
558 return createInteger(str);
559 } catch (NumberFormatException nfe) { // NOPMD
560 // ignore the bad number
581 exp = null;
582 }
583 if (dec == null && exp == null) { // no decimal point and no exponent
584 //Must be an Integer, Long, Biginteger
585 try {
586 return createInteger(str);
587 } catch (final NumberFormatException nfe) { // NOPMD
588 // ignore the bad number
589 }
590 try {
591 return createLong(str);
592 } catch (final NumberFormatException nfe) { // NOPMD
593 // ignore the bad number
594 }
595 return createBigInteger(str);
596 }
597
598 //Must be a Float, Double, BigDecimal
599 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
600 try {
601 if(numDecimals <= 7){// If number has 7 or fewer digits past the decimal point then make it a float
602 final Float f = createFloat(str);
603 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
604 return f;
561605 }
562 try {
563 return createLong(str);
564 } catch (NumberFormatException nfe) { // NOPMD
565 // ignore the bad number
606 }
607 } catch (final NumberFormatException nfe) { // NOPMD
608 // ignore the bad number
609 }
610 try {
611 if(numDecimals <= 16){// If number has between 8 and 16 digits past the decimal point then make it a double
612 final Double d = createDouble(str);
613 if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
614 return d;
566615 }
567 return createBigInteger(str);
568
569 } else {
570 //Must be a float,double,BigDec
571 boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
572 try {
573 Float f = createFloat(str);
574 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
575 return f;
576 }
577 } catch (NumberFormatException nfe) { // NOPMD
578 // ignore the bad number
579 }
580 try {
581 Double d = createDouble(str);
582 if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
583 return d;
584 }
585 } catch (NumberFormatException nfe) { // NOPMD
586 // ignore the bad number
587 }
588
589 return createBigDecimal(str);
590
591 }
592 }
616 }
617 } catch (final NumberFormatException nfe) { // NOPMD
618 // ignore the bad number
619 }
620
621 return createBigDecimal(str);
593622 }
594623
595624 /**
600629 * @param str the String to check
601630 * @return if it is all zeros or <code>null</code>
602631 */
603 private static boolean isAllZeros(String str) {
632 private static boolean isAllZeros(final String str) {
604633 if (str == null) {
605634 return true;
606635 }
619648 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
620649 *
621650 * @param str a <code>String</code> to convert, may be null
622 * @return converted <code>Float</code>
651 * @return converted <code>Float</code> (or null if the input is null)
623652 * @throws NumberFormatException if the value cannot be converted
624653 */
625 public static Float createFloat(String str) {
654 public static Float createFloat(final String str) {
626655 if (str == null) {
627656 return null;
628657 }
635664 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
636665 *
637666 * @param str a <code>String</code> to convert, may be null
638 * @return converted <code>Double</code>
667 * @return converted <code>Double</code> (or null if the input is null)
639668 * @throws NumberFormatException if the value cannot be converted
640669 */
641 public static Double createDouble(String str) {
670 public static Double createDouble(final String str) {
642671 if (str == null) {
643672 return null;
644673 }
652681 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
653682 *
654683 * @param str a <code>String</code> to convert, may be null
655 * @return converted <code>Integer</code>
684 * @return converted <code>Integer</code> (or null if the input is null)
656685 * @throws NumberFormatException if the value cannot be converted
657686 */
658 public static Integer createInteger(String str) {
687 public static Integer createInteger(final String str) {
659688 if (str == null) {
660689 return null;
661690 }
670699 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
671700 *
672701 * @param str a <code>String</code> to convert, may be null
673 * @return converted <code>Long</code>
702 * @return converted <code>Long</code> (or null if the input is null)
674703 * @throws NumberFormatException if the value cannot be converted
675704 */
676 public static Long createLong(String str) {
705 public static Long createLong(final String str) {
677706 if (str == null) {
678707 return null;
679708 }
681710 }
682711
683712 /**
684 * <p>Convert a <code>String</code> to a <code>BigInteger</code>.</p>
713 * <p>Convert a <code>String</code> to a <code>BigInteger</code>;
714 * since 3.2 it handles hex (0x or #) and octal (0) notations.</p>
685715 *
686716 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
687717 *
688718 * @param str a <code>String</code> to convert, may be null
689 * @return converted <code>BigInteger</code>
719 * @return converted <code>BigInteger</code> (or null if the input is null)
690720 * @throws NumberFormatException if the value cannot be converted
691721 */
692 public static BigInteger createBigInteger(String str) {
722 public static BigInteger createBigInteger(final String str) {
693723 if (str == null) {
694724 return null;
695725 }
696 return new BigInteger(str);
726 int pos = 0; // offset within string
727 int radix = 10;
728 boolean negate = false; // need to negate later?
729 if (str.startsWith("-")) {
730 negate = true;
731 pos = 1;
732 }
733 if (str.startsWith("0x", pos) || str.startsWith("0x", pos)) { // hex
734 radix = 16;
735 pos += 2;
736 } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer)
737 radix = 16;
738 pos ++;
739 } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits
740 radix = 8;
741 pos ++;
742 } // default is to treat as decimal
743
744 final BigInteger value = new BigInteger(str.substring(pos), radix);
745 return negate ? value.negate() : value;
697746 }
698747
699748 /**
702751 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
703752 *
704753 * @param str a <code>String</code> to convert, may be null
705 * @return converted <code>BigDecimal</code>
754 * @return converted <code>BigDecimal</code> (or null if the input is null)
706755 * @throws NumberFormatException if the value cannot be converted
707756 */
708 public static BigDecimal createBigDecimal(String str) {
757 public static BigDecimal createBigDecimal(final String str) {
709758 if (str == null) {
710759 return null;
711760 }
712761 // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
713762 if (StringUtils.isBlank(str)) {
714763 throw new NumberFormatException("A blank string is not a valid number");
715 }
764 }
765 if (str.trim().startsWith("--")) {
766 // this is protection for poorness in java.lang.BigDecimal.
767 // it accepts this as a legal value, but it does not appear
768 // to be in specification of class. OS X Java parses it to
769 // a wrong value.
770 throw new NumberFormatException(str + " is not a valid number.");
771 }
716772 return new BigDecimal(str);
717773 }
718774
726782 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
727783 * @throws IllegalArgumentException if <code>array</code> is empty
728784 */
729 public static long min(long[] array) {
785 public static long min(final long[] array) {
730786 // Validates input
731 if (array == null) {
732 throw new IllegalArgumentException("The Array must not be null");
733 } else if (array.length == 0) {
734 throw new IllegalArgumentException("Array cannot be empty.");
735 }
787 validateArray(array);
736788
737789 // Finds and returns min
738790 long min = array[0];
753805 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
754806 * @throws IllegalArgumentException if <code>array</code> is empty
755807 */
756 public static int min(int[] array) {
808 public static int min(final int[] array) {
757809 // Validates input
758 if (array == null) {
759 throw new IllegalArgumentException("The Array must not be null");
760 } else if (array.length == 0) {
761 throw new IllegalArgumentException("Array cannot be empty.");
762 }
810 validateArray(array);
763811
764812 // Finds and returns min
765813 int min = array[0];
780828 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
781829 * @throws IllegalArgumentException if <code>array</code> is empty
782830 */
783 public static short min(short[] array) {
831 public static short min(final short[] array) {
784832 // Validates input
785 if (array == null) {
786 throw new IllegalArgumentException("The Array must not be null");
787 } else if (array.length == 0) {
788 throw new IllegalArgumentException("Array cannot be empty.");
789 }
833 validateArray(array);
790834
791835 // Finds and returns min
792836 short min = array[0];
807851 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
808852 * @throws IllegalArgumentException if <code>array</code> is empty
809853 */
810 public static byte min(byte[] array) {
854 public static byte min(final byte[] array) {
811855 // Validates input
812 if (array == null) {
813 throw new IllegalArgumentException("The Array must not be null");
814 } else if (array.length == 0) {
815 throw new IllegalArgumentException("Array cannot be empty.");
816 }
856 validateArray(array);
817857
818858 // Finds and returns min
819859 byte min = array[0];
835875 * @throws IllegalArgumentException if <code>array</code> is empty
836876 * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently
837877 */
838 public static double min(double[] array) {
878 public static double min(final double[] array) {
839879 // Validates input
840 if (array == null) {
841 throw new IllegalArgumentException("The Array must not be null");
842 } else if (array.length == 0) {
843 throw new IllegalArgumentException("Array cannot be empty.");
844 }
880 validateArray(array);
845881
846882 // Finds and returns min
847883 double min = array[0];
866902 * @throws IllegalArgumentException if <code>array</code> is empty
867903 * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently
868904 */
869 public static float min(float[] array) {
905 public static float min(final float[] array) {
870906 // Validates input
871 if (array == null) {
872 throw new IllegalArgumentException("The Array must not be null");
873 } else if (array.length == 0) {
874 throw new IllegalArgumentException("Array cannot be empty.");
875 }
907 validateArray(array);
876908
877909 // Finds and returns min
878910 float min = array[0];
898930 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
899931 * @throws IllegalArgumentException if <code>array</code> is empty
900932 */
901 public static long max(long[] array) {
933 public static long max(final long[] array) {
902934 // Validates input
903 if (array == null) {
904 throw new IllegalArgumentException("The Array must not be null");
905 } else if (array.length == 0) {
906 throw new IllegalArgumentException("Array cannot be empty.");
907 }
935 validateArray(array);
908936
909937 // Finds and returns max
910938 long max = array[0];
925953 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
926954 * @throws IllegalArgumentException if <code>array</code> is empty
927955 */
928 public static int max(int[] array) {
956 public static int max(final int[] array) {
929957 // Validates input
930 if (array == null) {
931 throw new IllegalArgumentException("The Array must not be null");
932 } else if (array.length == 0) {
933 throw new IllegalArgumentException("Array cannot be empty.");
934 }
958 validateArray(array);
935959
936960 // Finds and returns max
937961 int max = array[0];
952976 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
953977 * @throws IllegalArgumentException if <code>array</code> is empty
954978 */
955 public static short max(short[] array) {
979 public static short max(final short[] array) {
956980 // Validates input
957 if (array == null) {
958 throw new IllegalArgumentException("The Array must not be null");
959 } else if (array.length == 0) {
960 throw new IllegalArgumentException("Array cannot be empty.");
961 }
981 validateArray(array);
962982
963983 // Finds and returns max
964984 short max = array[0];
979999 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
9801000 * @throws IllegalArgumentException if <code>array</code> is empty
9811001 */
982 public static byte max(byte[] array) {
1002 public static byte max(final byte[] array) {
9831003 // Validates input
984 if (array == null) {
985 throw new IllegalArgumentException("The Array must not be null");
986 } else if (array.length == 0) {
987 throw new IllegalArgumentException("Array cannot be empty.");
988 }
1004 validateArray(array);
9891005
9901006 // Finds and returns max
9911007 byte max = array[0];
10071023 * @throws IllegalArgumentException if <code>array</code> is empty
10081024 * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently
10091025 */
1010 public static double max(double[] array) {
1026 public static double max(final double[] array) {
10111027 // Validates input
1012 if (array== null) {
1013 throw new IllegalArgumentException("The Array must not be null");
1014 } else if (array.length == 0) {
1015 throw new IllegalArgumentException("Array cannot be empty.");
1016 }
1017
1028 validateArray(array);
1029
10181030 // Finds and returns max
10191031 double max = array[0];
10201032 for (int j = 1; j < array.length; j++) {
10381050 * @throws IllegalArgumentException if <code>array</code> is empty
10391051 * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently
10401052 */
1041 public static float max(float[] array) {
1053 public static float max(final float[] array) {
10421054 // Validates input
1043 if (array == null) {
1044 throw new IllegalArgumentException("The Array must not be null");
1045 } else if (array.length == 0) {
1046 throw new IllegalArgumentException("Array cannot be empty.");
1047 }
1055 validateArray(array);
10481056
10491057 // Finds and returns max
10501058 float max = array[0];
10591067
10601068 return max;
10611069 }
1070
1071 /**
1072 * Checks if the specified array is neither null nor empty.
1073 *
1074 * @param array the array to check
1075 * @throws IllegalArgumentException if {@code array} is either {@code null} or empty
1076 */
1077 private static void validateArray(final Object array) {
1078 if (array == null) {
1079 throw new IllegalArgumentException("The Array must not be null");
1080 } else if (Array.getLength(array) == 0) {
1081 throw new IllegalArgumentException("Array cannot be empty.");
1082 }
1083 }
10621084
10631085 // 3 param min
10641086 //-----------------------------------------------------------------------
10701092 * @param c value 3
10711093 * @return the smallest of the values
10721094 */
1073 public static long min(long a, long b, long c) {
1095 public static long min(long a, final long b, final long c) {
10741096 if (b < a) {
10751097 a = b;
10761098 }
10881110 * @param c value 3
10891111 * @return the smallest of the values
10901112 */
1091 public static int min(int a, int b, int c) {
1113 public static int min(int a, final int b, final int c) {
10921114 if (b < a) {
10931115 a = b;
10941116 }
11061128 * @param c value 3
11071129 * @return the smallest of the values
11081130 */
1109 public static short min(short a, short b, short c) {
1131 public static short min(short a, final short b, final short c) {
11101132 if (b < a) {
11111133 a = b;
11121134 }
11241146 * @param c value 3
11251147 * @return the smallest of the values
11261148 */
1127 public static byte min(byte a, byte b, byte c) {
1149 public static byte min(byte a, final byte b, final byte c) {
11281150 if (b < a) {
11291151 a = b;
11301152 }
11461168 * @return the smallest of the values
11471169 * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently
11481170 */
1149 public static double min(double a, double b, double c) {
1171 public static double min(final double a, final double b, final double c) {
11501172 return Math.min(Math.min(a, b), c);
11511173 }
11521174
11621184 * @return the smallest of the values
11631185 * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently
11641186 */
1165 public static float min(float a, float b, float c) {
1187 public static float min(final float a, final float b, final float c) {
11661188 return Math.min(Math.min(a, b), c);
11671189 }
11681190
11761198 * @param c value 3
11771199 * @return the largest of the values
11781200 */
1179 public static long max(long a, long b, long c) {
1201 public static long max(long a, final long b, final long c) {
11801202 if (b > a) {
11811203 a = b;
11821204 }
11941216 * @param c value 3
11951217 * @return the largest of the values
11961218 */
1197 public static int max(int a, int b, int c) {
1219 public static int max(int a, final int b, final int c) {
11981220 if (b > a) {
11991221 a = b;
12001222 }
12121234 * @param c value 3
12131235 * @return the largest of the values
12141236 */
1215 public static short max(short a, short b, short c) {
1237 public static short max(short a, final short b, final short c) {
12161238 if (b > a) {
12171239 a = b;
12181240 }
12301252 * @param c value 3
12311253 * @return the largest of the values
12321254 */
1233 public static byte max(byte a, byte b, byte c) {
1255 public static byte max(byte a, final byte b, final byte c) {
12341256 if (b > a) {
12351257 a = b;
12361258 }
12521274 * @return the largest of the values
12531275 * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently
12541276 */
1255 public static double max(double a, double b, double c) {
1277 public static double max(final double a, final double b, final double c) {
12561278 return Math.max(Math.max(a, b), c);
12571279 }
12581280
12681290 * @return the largest of the values
12691291 * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently
12701292 */
1271 public static float max(float a, float b, float c) {
1293 public static float max(final float a, final float b, final float c) {
12721294 return Math.max(Math.max(a, b), c);
12731295 }
12741296
12831305 * @param str the <code>String</code> to check
12841306 * @return <code>true</code> if str contains only Unicode numeric
12851307 */
1286 public static boolean isDigits(String str) {
1308 public static boolean isDigits(final String str) {
12871309 if (StringUtils.isEmpty(str)) {
12881310 return false;
12891311 }
13081330 * @param str the <code>String</code> to check
13091331 * @return <code>true</code> if the string is a correctly formatted number
13101332 */
1311 public static boolean isNumber(String str) {
1333 public static boolean isNumber(final String str) {
13121334 if (StringUtils.isEmpty(str)) {
13131335 return false;
13141336 }
1315 char[] chars = str.toCharArray();
1337 final char[] chars = str.toCharArray();
13161338 int sz = chars.length;
13171339 boolean hasExp = false;
13181340 boolean hasDecPoint = false;
13191341 boolean allowSigns = false;
13201342 boolean foundDigit = false;
13211343 // deal with any possible sign up front
1322 int start = (chars[0] == '-') ? 1 : 0;
1344 final int start = (chars[0] == '-') ? 1 : 0;
13231345 if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') {
13241346 int i = start + 2;
13251347 if (i == sz) {
2525 * effectively change the value of the primitive/string. Another use case is to store a frequently changing primitive in
2626 * a collection (for example a total in a map) without needing to create new Integer/Long wrapper objects.
2727 *
28 * @param <T> the type to set and get
2829 * @since 2.1
29 * @param <T> the type to set and get
30 * @version $Id: Mutable.java 1153213 2011-08-02 17:35:39Z ggregory $
30 * @version $Id: Mutable.java 1478488 2013-05-02 19:05:44Z ggregory $
3131 */
3232 public interface Mutable<T> {
3333
2525 *
2626 * @see Boolean
2727 * @since 2.2
28 * @version $Id: MutableBoolean.java 1160571 2011-08-23 07:36:08Z bayard $
28 * @version $Id: MutableBoolean.java 1436770 2013-01-22 07:09:45Z ggregory $
2929 */
3030 public class MutableBoolean implements Mutable<Boolean>, Serializable, Comparable<MutableBoolean> {
3131
5151 *
5252 * @param value the initial value to store
5353 */
54 public MutableBoolean(boolean value) {
54 public MutableBoolean(final boolean value) {
5555 super();
5656 this.value = value;
5757 }
6262 * @param value the initial value to store, not null
6363 * @throws NullPointerException if the object is null
6464 */
65 public MutableBoolean(Boolean value) {
65 public MutableBoolean(final Boolean value) {
6666 super();
6767 this.value = value.booleanValue();
6868 }
7373 *
7474 * @return the value as a Boolean, never null
7575 */
76 @Override
7677 public Boolean getValue() {
7778 return Boolean.valueOf(this.value);
7879 }
8283 *
8384 * @param value the value to set
8485 */
85 public void setValue(boolean value) {
86 public void setValue(final boolean value) {
8687 this.value = value;
8788 }
8889
9293 * @param value the value to set, not null
9394 * @throws NullPointerException if the object is null
9495 */
95 public void setValue(Boolean value) {
96 @Override
97 public void setValue(final Boolean value) {
9698 this.value = value.booleanValue();
9799 }
98100
148150 * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
149151 */
150152 @Override
151 public boolean equals(Object obj) {
153 public boolean equals(final Object obj) {
152154 if (obj instanceof MutableBoolean) {
153155 return value == ((MutableBoolean) obj).booleanValue();
154156 }
173175 * @return negative if this is less, zero if equal, positive if greater
174176 * where false is less than true
175177 */
176 public int compareTo(MutableBoolean other) {
177 boolean anotherVal = other.value;
178 @Override
179 public int compareTo(final MutableBoolean other) {
180 final boolean anotherVal = other.value;
178181 return value == anotherVal ? 0 : (value ? 1 : -1);
179182 }
180183
2222 *
2323 * @see Byte
2424 * @since 2.1
25 * @version $Id: MutableByte.java 1160571 2011-08-23 07:36:08Z bayard $
25 * @version $Id: MutableByte.java 1436770 2013-01-22 07:09:45Z ggregory $
2626 */
2727 public class MutableByte extends Number implements Comparable<MutableByte>, Mutable<Number> {
2828
4848 *
4949 * @param value the initial value to store
5050 */
51 public MutableByte(byte value) {
51 public MutableByte(final byte value) {
5252 super();
5353 this.value = value;
5454 }
5959 * @param value the initial value to store, not null
6060 * @throws NullPointerException if the object is null
6161 */
62 public MutableByte(Number value) {
62 public MutableByte(final Number value) {
6363 super();
6464 this.value = value.byteValue();
6565 }
7171 * @throws NumberFormatException if the string cannot be parsed into a byte
7272 * @since 2.5
7373 */
74 public MutableByte(String value) throws NumberFormatException {
74 public MutableByte(final String value) throws NumberFormatException {
7575 super();
7676 this.value = Byte.parseByte(value);
7777 }
8282 *
8383 * @return the value as a Byte, never null
8484 */
85 @Override
8586 public Byte getValue() {
8687 return Byte.valueOf(this.value);
8788 }
9192 *
9293 * @param value the value to set
9394 */
94 public void setValue(byte value) {
95 public void setValue(final byte value) {
9596 this.value = value;
9697 }
9798
101102 * @param value the value to set, not null
102103 * @throws NullPointerException if the object is null
103104 */
104 public void setValue(Number value) {
105 @Override
106 public void setValue(final Number value) {
105107 this.value = value.byteValue();
106108 }
107109
131133 * @param operand the value to add, not null
132134 * @since Commons Lang 2.2
133135 */
134 public void add(byte operand) {
136 public void add(final byte operand) {
135137 this.value += operand;
136138 }
137139
142144 * @throws NullPointerException if the object is null
143145 * @since Commons Lang 2.2
144146 */
145 public void add(Number operand) {
147 public void add(final Number operand) {
146148 this.value += operand.byteValue();
147149 }
148150
152154 * @param operand the value to subtract, not null
153155 * @since Commons Lang 2.2
154156 */
155 public void subtract(byte operand) {
157 public void subtract(final byte operand) {
156158 this.value -= operand;
157159 }
158160
163165 * @throws NullPointerException if the object is null
164166 * @since Commons Lang 2.2
165167 */
166 public void subtract(Number operand) {
168 public void subtract(final Number operand) {
167169 this.value -= operand.byteValue();
168170 }
169171
239241 * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
240242 */
241243 @Override
242 public boolean equals(Object obj) {
244 public boolean equals(final Object obj) {
243245 if (obj instanceof MutableByte) {
244246 return value == ((MutableByte) obj).byteValue();
245247 }
263265 * @param other the other mutable to compare to, not null
264266 * @return negative if this is less, zero if equal, positive if greater
265267 */
266 public int compareTo(MutableByte other) {
267 byte anotherVal = other.value;
268 @Override
269 public int compareTo(final MutableByte other) {
270 final byte anotherVal = other.value;
268271 return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
269272 }
270273
2222 *
2323 * @see Double
2424 * @since 2.1
25 * @version $Id: MutableDouble.java 1199894 2011-11-09 17:53:59Z ggregory $
25 * @version $Id: MutableDouble.java 1436770 2013-01-22 07:09:45Z ggregory $
2626 */
2727 public class MutableDouble extends Number implements Comparable<MutableDouble>, Mutable<Number> {
2828
4848 *
4949 * @param value the initial value to store
5050 */
51 public MutableDouble(double value) {
51 public MutableDouble(final double value) {
5252 super();
5353 this.value = value;
5454 }
5959 * @param value the initial value to store, not null
6060 * @throws NullPointerException if the object is null
6161 */
62 public MutableDouble(Number value) {
62 public MutableDouble(final Number value) {
6363 super();
6464 this.value = value.doubleValue();
6565 }
7171 * @throws NumberFormatException if the string cannot be parsed into a double
7272 * @since 2.5
7373 */
74 public MutableDouble(String value) throws NumberFormatException {
74 public MutableDouble(final String value) throws NumberFormatException {
7575 super();
7676 this.value = Double.parseDouble(value);
7777 }
8282 *
8383 * @return the value as a Double, never null
8484 */
85 @Override
8586 public Double getValue() {
8687 return Double.valueOf(this.value);
8788 }
9192 *
9293 * @param value the value to set
9394 */
94 public void setValue(double value) {
95 public void setValue(final double value) {
9596 this.value = value;
9697 }
9798
101102 * @param value the value to set, not null
102103 * @throws NullPointerException if the object is null
103104 */
104 public void setValue(Number value) {
105 @Override
106 public void setValue(final Number value) {
105107 this.value = value.doubleValue();
106108 }
107109
150152 * @param operand the value to add
151153 * @since Commons Lang 2.2
152154 */
153 public void add(double operand) {
155 public void add(final double operand) {
154156 this.value += operand;
155157 }
156158
161163 * @throws NullPointerException if the object is null
162164 * @since Commons Lang 2.2
163165 */
164 public void add(Number operand) {
166 public void add(final Number operand) {
165167 this.value += operand.doubleValue();
166168 }
167169
171173 * @param operand the value to subtract, not null
172174 * @since Commons Lang 2.2
173175 */
174 public void subtract(double operand) {
176 public void subtract(final double operand) {
175177 this.value -= operand;
176178 }
177179
182184 * @throws NullPointerException if the object is null
183185 * @since Commons Lang 2.2
184186 */
185 public void subtract(Number operand) {
187 public void subtract(final Number operand) {
186188 this.value -= operand.doubleValue();
187189 }
188190
269271 * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
270272 */
271273 @Override
272 public boolean equals(Object obj) {
274 public boolean equals(final Object obj) {
273275 return obj instanceof MutableDouble
274276 && Double.doubleToLongBits(((MutableDouble) obj).value) == Double.doubleToLongBits(value);
275277 }
281283 */
282284 @Override
283285 public int hashCode() {
284 long bits = Double.doubleToLongBits(value);
286 final long bits = Double.doubleToLongBits(value);
285287 return (int) (bits ^ bits >>> 32);
286288 }
287289
292294 * @param other the other mutable to compare to, not null
293295 * @return negative if this is less, zero if equal, positive if greater
294296 */
295 public int compareTo(MutableDouble other) {
296 double anotherVal = other.value;
297 @Override
298 public int compareTo(final MutableDouble other) {
299 final double anotherVal = other.value;
297300 return Double.compare(value, anotherVal);
298301 }
299302
2222 *
2323 * @see Float
2424 * @since 2.1
25 * @version $Id: MutableFloat.java 1199894 2011-11-09 17:53:59Z ggregory $
25 * @version $Id: MutableFloat.java 1436770 2013-01-22 07:09:45Z ggregory $
2626 */
2727 public class MutableFloat extends Number implements Comparable<MutableFloat>, Mutable<Number> {
2828
4848 *
4949 * @param value the initial value to store
5050 */
51 public MutableFloat(float value) {
51 public MutableFloat(final float value) {
5252 super();
5353 this.value = value;
5454 }
5959 * @param value the initial value to store, not null
6060 * @throws NullPointerException if the object is null
6161 */
62 public MutableFloat(Number value) {
62 public MutableFloat(final Number value) {
6363 super();
6464 this.value = value.floatValue();
6565 }
7171 * @throws NumberFormatException if the string cannot be parsed into a float
7272 * @since 2.5
7373 */
74 public MutableFloat(String value) throws NumberFormatException {
74 public MutableFloat(final String value) throws NumberFormatException {
7575 super();
7676 this.value = Float.parseFloat(value);
7777 }
8282 *
8383 * @return the value as a Float, never null
8484 */
85 @Override
8586 public Float getValue() {
8687 return Float.valueOf(this.value);
8788 }
9192 *
9293 * @param value the value to set
9394 */
94 public void setValue(float value) {
95 public void setValue(final float value) {
9596 this.value = value;
9697 }
9798
101102 * @param value the value to set, not null
102103 * @throws NullPointerException if the object is null
103104 */
104 public void setValue(Number value) {
105 @Override
106 public void setValue(final Number value) {
105107 this.value = value.floatValue();
106108 }
107109
150152 * @param operand the value to add, not null
151153 * @since Commons Lang 2.2
152154 */
153 public void add(float operand) {
155 public void add(final float operand) {
154156 this.value += operand;
155157 }
156158
161163 * @throws NullPointerException if the object is null
162164 * @since Commons Lang 2.2
163165 */
164 public void add(Number operand) {
166 public void add(final Number operand) {
165167 this.value += operand.floatValue();
166168 }
167169
171173 * @param operand the value to subtract
172174 * @since Commons Lang 2.2
173175 */
174 public void subtract(float operand) {
176 public void subtract(final float operand) {
175177 this.value -= operand;
176178 }
177179
182184 * @throws NullPointerException if the object is null
183185 * @since Commons Lang 2.2
184186 */
185 public void subtract(Number operand) {
187 public void subtract(final Number operand) {
186188 this.value -= operand.floatValue();
187189 }
188190
271273 * @see java.lang.Float#floatToIntBits(float)
272274 */
273275 @Override
274 public boolean equals(Object obj) {
276 public boolean equals(final Object obj) {
275277 return obj instanceof MutableFloat
276278 && Float.floatToIntBits(((MutableFloat) obj).value) == Float.floatToIntBits(value);
277279 }
293295 * @param other the other mutable to compare to, not null
294296 * @return negative if this is less, zero if equal, positive if greater
295297 */
296 public int compareTo(MutableFloat other) {
297 float anotherVal = other.value;
298 @Override
299 public int compareTo(final MutableFloat other) {
300 final float anotherVal = other.value;
298301 return Float.compare(value, anotherVal);
299302 }
300303
2222 *
2323 * @see Integer
2424 * @since 2.1
25 * @version $Id: MutableInt.java 1160571 2011-08-23 07:36:08Z bayard $
25 * @version $Id: MutableInt.java 1436770 2013-01-22 07:09:45Z ggregory $
2626 */
2727 public class MutableInt extends Number implements Comparable<MutableInt>, Mutable<Number> {
2828
4848 *
4949 * @param value the initial value to store
5050 */
51 public MutableInt(int value) {
51 public MutableInt(final int value) {
5252 super();
5353 this.value = value;
5454 }
5959 * @param value the initial value to store, not null
6060 * @throws NullPointerException if the object is null
6161 */
62 public MutableInt(Number value) {
62 public MutableInt(final Number value) {
6363 super();
6464 this.value = value.intValue();
6565 }
7171 * @throws NumberFormatException if the string cannot be parsed into an int
7272 * @since 2.5
7373 */
74 public MutableInt(String value) throws NumberFormatException {
74 public MutableInt(final String value) throws NumberFormatException {
7575 super();
7676 this.value = Integer.parseInt(value);
7777 }
8282 *
8383 * @return the value as a Integer, never null
8484 */
85 @Override
8586 public Integer getValue() {
8687 return Integer.valueOf(this.value);
8788 }
9192 *
9293 * @param value the value to set
9394 */
94 public void setValue(int value) {
95 public void setValue(final int value) {
9596 this.value = value;
9697 }
9798
101102 * @param value the value to set, not null
102103 * @throws NullPointerException if the object is null
103104 */
104 public void setValue(Number value) {
105 @Override
106 public void setValue(final Number value) {
105107 this.value = value.intValue();
106108 }
107109
131133 * @param operand the value to add, not null
132134 * @since Commons Lang 2.2
133135 */
134 public void add(int operand) {
136 public void add(final int operand) {
135137 this.value += operand;
136138 }
137139
142144 * @throws NullPointerException if the object is null
143145 * @since Commons Lang 2.2
144146 */
145 public void add(Number operand) {
147 public void add(final Number operand) {
146148 this.value += operand.intValue();
147149 }
148150
152154 * @param operand the value to subtract, not null
153155 * @since Commons Lang 2.2
154156 */
155 public void subtract(int operand) {
157 public void subtract(final int operand) {
156158 this.value -= operand;
157159 }
158160
163165 * @throws NullPointerException if the object is null
164166 * @since Commons Lang 2.2
165167 */
166 public void subtract(Number operand) {
168 public void subtract(final Number operand) {
167169 this.value -= operand.intValue();
168170 }
169171
229231 * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
230232 */
231233 @Override
232 public boolean equals(Object obj) {
234 public boolean equals(final Object obj) {
233235 if (obj instanceof MutableInt) {
234236 return value == ((MutableInt) obj).intValue();
235237 }
253255 * @param other the other mutable to compare to, not null
254256 * @return negative if this is less, zero if equal, positive if greater
255257 */
256 public int compareTo(MutableInt other) {
257 int anotherVal = other.value;
258 @Override
259 public int compareTo(final MutableInt other) {
260 final int anotherVal = other.value;
258261 return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
259262 }
260263
2222 *
2323 * @see Long
2424 * @since 2.1
25 * @version $Id: MutableLong.java 1160571 2011-08-23 07:36:08Z bayard $
25 * @version $Id: MutableLong.java 1436770 2013-01-22 07:09:45Z ggregory $
2626 */
2727 public class MutableLong extends Number implements Comparable<MutableLong>, Mutable<Number> {
2828
4848 *
4949 * @param value the initial value to store
5050 */
51 public MutableLong(long value) {
51 public MutableLong(final long value) {
5252 super();
5353 this.value = value;
5454 }
5959 * @param value the initial value to store, not null
6060 * @throws NullPointerException if the object is null
6161 */
62 public MutableLong(Number value) {
62 public MutableLong(final Number value) {
6363 super();
6464 this.value = value.longValue();
6565 }
7171 * @throws NumberFormatException if the string cannot be parsed into a long
7272 * @since 2.5
7373 */
74 public MutableLong(String value) throws NumberFormatException {
74 public MutableLong(final String value) throws NumberFormatException {
7575 super();
7676 this.value = Long.parseLong(value);
7777 }
8282 *
8383 * @return the value as a Long, never null
8484 */
85 @Override
8586 public Long getValue() {
8687 return Long.valueOf(this.value);
8788 }
9192 *
9293 * @param value the value to set
9394 */
94 public void setValue(long value) {
95 public void setValue(final long value) {
9596 this.value = value;
9697 }
9798
101102 * @param value the value to set, not null
102103 * @throws NullPointerException if the object is null
103104 */
104 public void setValue(Number value) {
105 @Override
106 public void setValue(final Number value) {
105107 this.value = value.longValue();
106108 }
107109
131133 * @param operand the value to add, not null
132134 * @since Commons Lang 2.2
133135 */
134 public void add(long operand) {
136 public void add(final long operand) {
135137 this.value += operand;
136138 }
137139
142144 * @throws NullPointerException if the object is null
143145 * @since Commons Lang 2.2
144146 */
145 public void add(Number operand) {
147 public void add(final Number operand) {
146148 this.value += operand.longValue();
147149 }
148150
152154 * @param operand the value to subtract, not null
153155 * @since Commons Lang 2.2
154156 */
155 public void subtract(long operand) {
157 public void subtract(final long operand) {
156158 this.value -= operand;
157159 }
158160
163165 * @throws NullPointerException if the object is null
164166 * @since Commons Lang 2.2
165167 */
166 public void subtract(Number operand) {
168 public void subtract(final Number operand) {
167169 this.value -= operand.longValue();
168170 }
169171
229231 * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
230232 */
231233 @Override
232 public boolean equals(Object obj) {
234 public boolean equals(final Object obj) {
233235 if (obj instanceof MutableLong) {
234236 return value == ((MutableLong) obj).longValue();
235237 }
253255 * @param other the other mutable to compare to, not null
254256 * @return negative if this is less, zero if equal, positive if greater
255257 */
256 public int compareTo(MutableLong other) {
257 long anotherVal = other.value;
258 @Override
259 public int compareTo(final MutableLong other) {
260 final long anotherVal = other.value;
258261 return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
259262 }
260263
2121 /**
2222 * A mutable <code>Object</code> wrapper.
2323 *
24 * @param <T> the type to set and get
2425 * @since 2.1
25 * @version $Id: MutableObject.java 1088899 2011-04-05 05:31:27Z bayard $
26 * @version $Id: MutableObject.java 1478488 2013-05-02 19:05:44Z ggregory $
2627 */
2728 public class MutableObject<T> implements Mutable<T>, Serializable {
2829
4849 *
4950 * @param value the initial value to store
5051 */
51 public MutableObject(T value) {
52 public MutableObject(final T value) {
5253 super();
5354 this.value = value;
5455 }
5960 *
6061 * @return the value, may be null
6162 */
63 @Override
6264 public T getValue() {
6365 return this.value;
6466 }
6870 *
6971 * @param value the value to set
7072 */
71 public void setValue(T value) {
73 @Override
74 public void setValue(final T value) {
7275 this.value = value;
7376 }
7477
8689 * <code>false</code> otherwise.
8790 */
8891 @Override
89 public boolean equals(Object obj) {
92 public boolean equals(final Object obj) {
9093 if (obj == null) {
9194 return false;
9295 }
9497 return true;
9598 }
9699 if (this.getClass() == obj.getClass()) {
97 MutableObject<?> that = (MutableObject<?>) obj;
100 final MutableObject<?> that = (MutableObject<?>) obj;
98101 return this.value.equals(that.value);
99102 } else {
100103 return false;
2222 *
2323 * @see Short
2424 * @since 2.1
25 * @version $Id: MutableShort.java 1160571 2011-08-23 07:36:08Z bayard $
25 * @version $Id: MutableShort.java 1436770 2013-01-22 07:09:45Z ggregory $
2626 */
2727 public class MutableShort extends Number implements Comparable<MutableShort>, Mutable<Number> {
2828
4848 *
4949 * @param value the initial value to store
5050 */
51 public MutableShort(short value) {
51 public MutableShort(final short value) {
5252 super();
5353 this.value = value;
5454 }
5959 * @param value the initial value to store, not null
6060 * @throws NullPointerException if the object is null
6161 */
62 public MutableShort(Number value) {
62 public MutableShort(final Number value) {
6363 super();
6464 this.value = value.shortValue();
6565 }
7171 * @throws NumberFormatException if the string cannot be parsed into a short
7272 * @since 2.5
7373 */
74 public MutableShort(String value) throws NumberFormatException {
74 public MutableShort(final String value) throws NumberFormatException {
7575 super();
7676 this.value = Short.parseShort(value);
7777 }
8282 *
8383 * @return the value as a Short, never null
8484 */
85 @Override
8586 public Short getValue() {
8687 return Short.valueOf(this.value);
8788 }
9192 *
9293 * @param value the value to set
9394 */
94 public void setValue(short value) {
95 public void setValue(final short value) {
9596 this.value = value;
9697 }
9798
101102 * @param value the value to set, not null
102103 * @throws NullPointerException if the object is null
103104 */
104 public void setValue(Number value) {
105 @Override
106 public void setValue(final Number value) {
105107 this.value = value.shortValue();
106108 }
107109
131133 * @param operand the value to add, not null
132134 * @since Commons Lang 2.2
133135 */
134 public void add(short operand) {
136 public void add(final short operand) {
135137 this.value += operand;
136138 }
137139
142144 * @throws NullPointerException if the object is null
143145 * @since Commons Lang 2.2
144146 */
145 public void add(Number operand) {
147 public void add(final Number operand) {
146148 this.value += operand.shortValue();
147149 }
148150
152154 * @param operand the value to subtract, not null
153155 * @since Commons Lang 2.2
154156 */
155 public void subtract(short operand) {
157 public void subtract(final short operand) {
156158 this.value -= operand;
157159 }
158160
163165 * @throws NullPointerException if the object is null
164166 * @since Commons Lang 2.2
165167 */
166 public void subtract(Number operand) {
168 public void subtract(final Number operand) {
167169 this.value -= operand.shortValue();
168170 }
169171
239241 * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
240242 */
241243 @Override
242 public boolean equals(Object obj) {
244 public boolean equals(final Object obj) {
243245 if (obj instanceof MutableShort) {
244246 return value == ((MutableShort) obj).shortValue();
245247 }
263265 * @param other the other mutable to compare to, not null
264266 * @return negative if this is less, zero if equal, positive if greater
265267 */
266 public int compareTo(MutableShort other) {
267 short anotherVal = other.value;
268 @Override
269 public int compareTo(final MutableShort other) {
270 final short anotherVal = other.value;
268271 return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
269272 }
270273
2121
2222 import org.apache.commons.lang3.ArrayUtils;
2323 import org.apache.commons.lang3.ClassUtils;
24 import org.apache.commons.lang3.Validate;
2425
2526 /**
2627 * <p> Utility reflection methods focused on constructors, modeled after
2728 * {@link MethodUtils}. </p>
2829 *
2930 * <h3>Known Limitations</h3> <h4>Accessing Public Constructors In A Default
30 * Access Superclass</h4> <p>There is an issue when invoking public constructors
31 * contained in a default access superclass. Reflection locates these
32 * constructors fine and correctly assigns them as public. However, an
33 * <code>IllegalAccessException</code> is thrown if the constructors is
31 * Access Superclass</h4> <p>There is an issue when invoking {@code public} constructors
32 * contained in a default access superclass. Reflection correctly locates these
33 * constructors and assigns them as {@code public}. However, an
34 * {@link IllegalAccessException} is thrown if the constructor is
3435 * invoked.</p>
3536 *
36 * <p><code>ConstructorUtils</code> contains a workaround for this situation. It
37 * will attempt to call <code>setAccessible</code> on this constructor. If this
37 * <p>{@link ConstructorUtils} contains a workaround for this situation: it
38 * will attempt to call {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} on this constructor. If this
3839 * call succeeds, then the method can be invoked as normal. This call will only
3940 * succeed when the application has sufficient security privileges. If this call
4041 * fails then a warning will be logged and the method may fail.</p>
4142 *
4243 * @since 2.5
43 * @version $Id: ConstructorUtils.java 1144010 2011-07-07 20:02:10Z joehni $
44 * @version $Id: ConstructorUtils.java 1534831 2013-10-22 22:41:06Z mbenson $
4445 */
4546 public class ConstructorUtils {
4647
4748 /**
4849 * <p>ConstructorUtils instances should NOT be constructed in standard
4950 * programming. Instead, the class should be used as
50 * <code>ConstructorUtils.invokeConstructor(cls, args)</code>.</p>
51 *
52 * <p>This constructor is public to permit tools that require a JavaBean
51 * {@code ConstructorUtils.invokeConstructor(cls, args)}.</p>
52 *
53 * <p>This constructor is {@code public} to permit tools that require a JavaBean
5354 * instance to operate.</p>
5455 */
5556 public ConstructorUtils() {
6465 * The constructor signature must match the argument types by assignment compatibility.</p>
6566 *
6667 * @param <T> the type to be constructed
67 * @param cls the class to be constructed, not null
68 * @param args the array of arguments, null treated as empty
69 * @return new instance of <code>cls</code>, not null
70 *
68 * @param cls the class to be constructed, not {@code null}
69 * @param args the array of arguments, {@code null} treated as empty
70 * @return new instance of {@code cls}, not {@code null}
71 *
72 * @throws NullPointerException if {@code cls} is {@code null}
7173 * @throws NoSuchMethodException if a matching constructor cannot be found
7274 * @throws IllegalAccessException if invocation is not permitted by security
7375 * @throws InvocationTargetException if an error occurs on invocation
7476 * @throws InstantiationException if an error occurs on instantiation
7577 * @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
7678 */
77 public static <T> T invokeConstructor(Class<T> cls, Object... args)
79 public static <T> T invokeConstructor(final Class<T> cls, Object... args)
7880 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
7981 InstantiationException {
80 if (args == null) {
81 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
82 }
83 Class<?> parameterTypes[] = new Class[args.length];
84 for (int i = 0; i < args.length; i++) {
85 parameterTypes[i] = args[i].getClass();
86 }
82 args = ArrayUtils.nullToEmpty(args);
83 final Class<?> parameterTypes[] = ClassUtils.toClass(args);
8784 return invokeConstructor(cls, args, parameterTypes);
8885 }
8986
9592 * The constructor signature must match the parameter types by assignment compatibility.</p>
9693 *
9794 * @param <T> the type to be constructed
98 * @param cls the class to be constructed, not null
99 * @param args the array of arguments, null treated as empty
100 * @param parameterTypes the array of parameter types, null treated as empty
101 * @return new instance of <code>cls</code>, not null
102 *
95 * @param cls the class to be constructed, not {@code null}
96 * @param args the array of arguments, {@code null} treated as empty
97 * @param parameterTypes the array of parameter types, {@code null} treated as empty
98 * @return new instance of {@code cls}, not {@code null}
99 *
100 * @throws NullPointerException if {@code cls} is {@code null}
103101 * @throws NoSuchMethodException if a matching constructor cannot be found
104102 * @throws IllegalAccessException if invocation is not permitted by security
105103 * @throws InvocationTargetException if an error occurs on invocation
106104 * @throws InstantiationException if an error occurs on instantiation
107105 * @see Constructor#newInstance
108106 */
109 public static <T> T invokeConstructor(Class<T> cls, Object[] args, Class<?>[] parameterTypes)
107 public static <T> T invokeConstructor(final Class<T> cls, Object[] args, Class<?>[] parameterTypes)
110108 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
111109 InstantiationException {
112 if (parameterTypes == null) {
113 parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
114 }
115 if (args == null) {
116 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
117 }
118 Constructor<T> ctor = getMatchingAccessibleConstructor(cls, parameterTypes);
110 args = ArrayUtils.nullToEmpty(args);
111 parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
112 final Constructor<T> ctor = getMatchingAccessibleConstructor(cls, parameterTypes);
119113 if (ctor == null) {
120114 throw new NoSuchMethodException(
121115 "No such accessible constructor on object: " + cls.getName());
131125 * The constructor signature must match the argument types exactly.</p>
132126 *
133127 * @param <T> the type to be constructed
134 * @param cls the class to be constructed, not null
135 * @param args the array of arguments, null treated as empty
136 * @return new instance of <code>cls</code>, not null
137 *
128 * @param cls the class to be constructed, not {@code null}
129 * @param args the array of arguments, {@code null} treated as empty
130 * @return new instance of {@code cls}, not {@code null}
131 *
132 * @throws NullPointerException if {@code cls} is {@code null}
138133 * @throws NoSuchMethodException if a matching constructor cannot be found
139134 * @throws IllegalAccessException if invocation is not permitted by security
140135 * @throws InvocationTargetException if an error occurs on invocation
141136 * @throws InstantiationException if an error occurs on instantiation
142137 * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
143138 */
144 public static <T> T invokeExactConstructor(Class<T> cls, Object... args)
139 public static <T> T invokeExactConstructor(final Class<T> cls, Object... args)
145140 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
146141 InstantiationException {
147 if (args == null) {
148 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
149 }
150 int arguments = args.length;
151 Class<?> parameterTypes[] = new Class[arguments];
152 for (int i = 0; i < arguments; i++) {
153 parameterTypes[i] = args[i].getClass();
154 }
142 args = ArrayUtils.nullToEmpty(args);
143 final Class<?> parameterTypes[] = ClassUtils.toClass(args);
155144 return invokeExactConstructor(cls, args, parameterTypes);
156145 }
157146
163152 * The constructor signature must match the parameter types exactly.</p>
164153 *
165154 * @param <T> the type to be constructed
166 * @param cls the class to be constructed, not null
167 * @param args the array of arguments, null treated as empty
168 * @param parameterTypes the array of parameter types, null treated as empty
169 * @return new instance of <code>cls</code>, not null
170 *
155 * @param cls the class to be constructed, not {@code null}
156 * @param args the array of arguments, {@code null} treated as empty
157 * @param parameterTypes the array of parameter types, {@code null} treated as empty
158 * @return new instance of <code>cls</code>, not {@code null}
159 *
160 * @throws NullPointerException if {@code cls} is {@code null}
171161 * @throws NoSuchMethodException if a matching constructor cannot be found
172162 * @throws IllegalAccessException if invocation is not permitted by security
173163 * @throws InvocationTargetException if an error occurs on invocation
174164 * @throws InstantiationException if an error occurs on instantiation
175165 * @see Constructor#newInstance
176166 */
177 public static <T> T invokeExactConstructor(Class<T> cls, Object[] args,
167 public static <T> T invokeExactConstructor(final Class<T> cls, Object[] args,
178168 Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException,
179169 InvocationTargetException, InstantiationException {
180 if (args == null) {
181 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
182 }
183 if (parameterTypes == null) {
184 parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
185 }
186 Constructor<T> ctor = getAccessibleConstructor(cls, parameterTypes);
170 args = ArrayUtils.nullToEmpty(args);
171 parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
172 final Constructor<T> ctor = getAccessibleConstructor(cls, parameterTypes);
187173 if (ctor == null) {
188174 throw new NoSuchMethodException(
189175 "No such accessible constructor on object: "+ cls.getName());
199185 * The constructor signature must match the parameter types exactly.</p>
200186 *
201187 * @param <T> the constructor type
202 * @param cls the class to find a constructor for, not null
203 * @param parameterTypes the array of parameter types, null treated as empty
204 * @return the constructor, null if no matching accessible constructor found
188 * @param cls the class to find a constructor for, not {@code null}
189 * @param parameterTypes the array of parameter types, {@code null} treated as empty
190 * @return the constructor, {@code null} if no matching accessible constructor found
205191 * @see Class#getConstructor
206192 * @see #getAccessibleConstructor(java.lang.reflect.Constructor)
207 */
208 public static <T> Constructor<T> getAccessibleConstructor(Class<T> cls,
209 Class<?>... parameterTypes) {
193 * @throws NullPointerException if {@code cls} is {@code null}
194 */
195 public static <T> Constructor<T> getAccessibleConstructor(final Class<T> cls,
196 final Class<?>... parameterTypes) {
197 Validate.notNull(cls, "class cannot be null");
210198 try {
211199 return getAccessibleConstructor(cls.getConstructor(parameterTypes));
212 } catch (NoSuchMethodException e) {
200 } catch (final NoSuchMethodException e) {
213201 return null;
214202 }
215203 }
220208 * <p>This simply ensures that the constructor is accessible.</p>
221209 *
222210 * @param <T> the constructor type
223 * @param ctor the prototype constructor object, not null
224 * @return the constructor, null if no matching accessible constructor found
211 * @param ctor the prototype constructor object, not {@code null}
212 * @return the constructor, {@code null} if no matching accessible constructor found
225213 * @see java.lang.SecurityManager
226 */
227 public static <T> Constructor<T> getAccessibleConstructor(Constructor<T> ctor) {
214 * @throws NullPointerException if {@code ctor} is {@code null}
215 */
216 public static <T> Constructor<T> getAccessibleConstructor(final Constructor<T> ctor) {
217 Validate.notNull(ctor, "constructor cannot be null");
228218 return MemberUtils.isAccessible(ctor)
229219 && Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) ? ctor : null;
230220 }
238228 *
239229 * <p>First it checks if there is a constructor matching the exact signature.
240230 * If not then all the constructors of the class are checked to see if their
241 * signatures are assignment compatible with the parameter types.
242 * The first assignment compatible matching constructor is returned.</p>
231 * signatures are assignment-compatible with the parameter types.
232 * The first assignment-compatible matching constructor is returned.</p>
243233 *
244234 * @param <T> the constructor type
245 * @param cls the class to find a constructor for, not null
235 * @param cls the class to find a constructor for, not {@code null}
246236 * @param parameterTypes find method with compatible parameters
247237 * @return the constructor, null if no matching accessible constructor found
248 */
249 public static <T> Constructor<T> getMatchingAccessibleConstructor(Class<T> cls,
250 Class<?>... parameterTypes) {
238 * @throws NullPointerException if {@code cls} is {@code null}
239 */
240 public static <T> Constructor<T> getMatchingAccessibleConstructor(final Class<T> cls,
241 final Class<?>... parameterTypes) {
242 Validate.notNull(cls, "class cannot be null");
251243 // see if we can find the constructor directly
252244 // most of the time this works and it's much faster
253245 try {
254 Constructor<T> ctor = cls.getConstructor(parameterTypes);
246 final Constructor<T> ctor = cls.getConstructor(parameterTypes);
255247 MemberUtils.setAccessibleWorkaround(ctor);
256248 return ctor;
257 } catch (NoSuchMethodException e) { // NOPMD - Swallow
249 } catch (final NoSuchMethodException e) { // NOPMD - Swallow
258250 }
259251 Constructor<T> result = null;
260252 /*
261253 * (1) Class.getConstructors() is documented to return Constructor<T> so as
262254 * long as the array is not subsequently modified, everything's fine.
263255 */
264 Constructor<?>[] ctors = cls.getConstructors();
256 final Constructor<?>[] ctors = cls.getConstructors();
265257
266258 // return best match:
267259 for (Constructor<?> ctor : ctors) {
276268 .getParameterTypes(), parameterTypes) < 0) {
277269 // temporary variable for annotation, see comment above (1)
278270 @SuppressWarnings("unchecked")
271 final
279272 Constructor<T> constructor = (Constructor<T>)ctor;
280273 result = constructor;
281274 }
1515 */
1616 package org.apache.commons.lang3.reflect;
1717
18 import org.apache.commons.lang3.ClassUtils;
19 import org.apache.commons.lang3.StringUtils;
20 import org.apache.commons.lang3.Validate;
21
1822 import java.lang.reflect.Field;
1923 import java.lang.reflect.Modifier;
20
21 import org.apache.commons.lang3.ClassUtils;
24 import java.util.ArrayList;
25 import java.util.List;
2226
2327 /**
24 * Utilities for working with fields by reflection. Adapted and refactored
25 * from the dormant [reflect] Commons sandbox component.
28 * Utilities for working with {@link Field}s by reflection. Adapted and refactored from the dormant [reflect] Commons sandbox
29 * component.
2630 * <p>
27 * The ability is provided to break the scoping restrictions coded by the
28 * programmer. This can allow fields to be changed that shouldn't be. This
29 * facility should be used with care.
30 *
31 * The ability is provided to break the scoping restrictions coded by the programmer. This can allow fields to be
32 * changed that shouldn't be. This facility should be used with care.
33 *
3134 * @since 2.5
32 * @version $Id: FieldUtils.java 1144929 2011-07-10 18:26:16Z ggregory $
35 * @version $Id: FieldUtils.java 1546799 2013-12-01 10:34:02Z mcucchiara $
3336 */
3437 public class FieldUtils {
3538
3639 /**
37 * FieldUtils instances should NOT be constructed in standard programming.
40 * {@link FieldUtils} instances should NOT be constructed in standard programming.
3841 * <p>
39 * This constructor is public to permit tools that require a JavaBean instance
40 * to operate.
42 * This constructor is {@code public} to permit tools that require a JavaBean instance to operate.</p>
4143 */
4244 public FieldUtils() {
4345 super();
4446 }
4547
4648 /**
47 * Gets an accessible <code>Field</code> by name respecting scope.
48 * Superclasses/interfaces will be considered.
49 *
50 * @param cls the class to reflect, must not be null
51 * @param fieldName the field name to obtain
49 * Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered.
50 *
51 * @param cls
52 * the {@link Class} to reflect, must not be {@code null}
53 * @param fieldName
54 * the field name to obtain
5255 * @return the Field object
53 * @throws IllegalArgumentException if the class or field name is null
54 */
55 public static Field getField(Class<?> cls, String fieldName) {
56 Field field = getField(cls, fieldName, false);
56 * @throws IllegalArgumentException
57 * if the class is {@code null}, or the field name is blank or empty
58 */
59 public static Field getField(final Class<?> cls, final String fieldName) {
60 final Field field = getField(cls, fieldName, false);
5761 MemberUtils.setAccessibleWorkaround(field);
5862 return field;
5963 }
6064
6165 /**
62 * Gets an accessible <code>Field</code> by name breaking scope
63 * if requested. Superclasses/interfaces will be considered.
64 *
65 * @param cls the class to reflect, must not be null
66 * @param fieldName the field name to obtain
67 * @param forceAccess whether to break scope restrictions using the
68 * <code>setAccessible</code> method. <code>False</code> will only
69 * match public fields.
66 * Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be
67 * considered.
68 *
69 * @param cls
70 * the {@link Class} to reflect, must not be {@code null}
71 * @param fieldName
72 * the field name to obtain
73 * @param forceAccess
74 * whether to break scope restrictions using the
75 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
76 * {@code false} will only match {@code public} fields.
7077 * @return the Field object
71 * @throws IllegalArgumentException if the class or field name is null
72 */
73 public static Field getField(final Class<?> cls, String fieldName, boolean forceAccess) {
74 if (cls == null) {
75 throw new IllegalArgumentException("The class must not be null");
76 }
77 if (fieldName == null) {
78 throw new IllegalArgumentException("The field name must not be null");
79 }
78 * @throws IllegalArgumentException
79 * if the class is {@code null}, or the field name is blank or empty or is matched at
80 * multiple places in the inheritance hierarchy
81 */
82 public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
83 Validate.isTrue(cls != null, "The class must not be null");
84 Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
8085 // Sun Java 1.3 has a bugged implementation of getField hence we write the
8186 // code ourselves
8287
8792 // priority order for lookup:
8893 // searchclass private/protected/package/public
8994 // superclass protected/package/public
90 // private/different package blocks access to further superclasses
95 // private/different package blocks access to further superclasses
9196 // implementedinterface public
9297
9398 // check up the superclass hierarchy
9499 for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) {
95100 try {
96 Field field = acls.getDeclaredField(fieldName);
101 final Field field = acls.getDeclaredField(fieldName);
97102 // getDeclaredField checks for non-public scopes as well
98103 // and it returns accurate results
99104 if (!Modifier.isPublic(field.getModifiers())) {
104109 }
105110 }
106111 return field;
107 } catch (NoSuchFieldException ex) { // NOPMD
112 } catch (final NoSuchFieldException ex) { // NOPMD
108113 // ignore
109114 }
110115 }
112117 // incase there is a public supersuperclass field hidden by a private/package
113118 // superclass field.
114119 Field match = null;
115 for (Class<?> class1 : ClassUtils.getAllInterfaces(cls)) {
120 for (final Class<?> class1 : ClassUtils.getAllInterfaces(cls)) {
116121 try {
117 Field test = ((Class<?>) class1).getField(fieldName);
118 if (match != null) {
119 throw new IllegalArgumentException("Reference to field " + fieldName + " is ambiguous relative to " + cls
120 + "; a matching field exists on two or more implemented interfaces.");
121 }
122 final Field test = class1.getField(fieldName);
123 Validate.isTrue(match == null, "Reference to field %s is ambiguous relative to %s"
124 + "; a matching field exists on two or more implemented interfaces.", fieldName, cls);
122125 match = test;
123 } catch (NoSuchFieldException ex) { // NOPMD
126 } catch (final NoSuchFieldException ex) { // NOPMD
124127 // ignore
125128 }
126129 }
128131 }
129132
130133 /**
131 * Gets an accessible <code>Field</code> by name respecting scope.
132 * Only the specified class will be considered.
133 *
134 * @param cls the class to reflect, must not be null
135 * @param fieldName the field name to obtain
134 * Gets an accessible {@link Field} by name respecting scope. Only the specified class will be considered.
135 *
136 * @param cls
137 * the {@link Class} to reflect, must not be {@code null}
138 * @param fieldName
139 * the field name to obtain
136140 * @return the Field object
137 * @throws IllegalArgumentException if the class or field name is null
138 */
139 public static Field getDeclaredField(Class<?> cls, String fieldName) {
141 * @throws IllegalArgumentException
142 * if the class is {@code null}, or the field name is blank or empty
143 */
144 public static Field getDeclaredField(final Class<?> cls, final String fieldName) {
140145 return getDeclaredField(cls, fieldName, false);
141146 }
142147
143148 /**
144 * Gets an accessible <code>Field</code> by name breaking scope
145 * if requested. Only the specified class will be considered.
146 *
147 * @param cls the class to reflect, must not be null
148 * @param fieldName the field name to obtain
149 * @param forceAccess whether to break scope restrictions using the
150 * <code>setAccessible</code> method. False will only match public fields.
149 * Gets an accessible {@link Field} by name, breaking scope if requested. Only the specified class will be
150 * considered.
151 *
152 * @param cls
153 * the {@link Class} to reflect, must not be {@code null}
154 * @param fieldName
155 * the field name to obtain
156 * @param forceAccess
157 * whether to break scope restrictions using the
158 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
159 * {@code false} will only match {@code public} fields.
151160 * @return the Field object
152 * @throws IllegalArgumentException if the class or field name is null
153 */
154 public static Field getDeclaredField(Class<?> cls, String fieldName, boolean forceAccess) {
155 if (cls == null) {
156 throw new IllegalArgumentException("The class must not be null");
157 }
158 if (fieldName == null) {
159 throw new IllegalArgumentException("The field name must not be null");
160 }
161 * @throws IllegalArgumentException
162 * if the class is {@code null}, or the field name is blank or empty
163 */
164 public static Field getDeclaredField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
165 Validate.isTrue(cls != null, "The class must not be null");
166 Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
161167 try {
162168 // only consider the specified class by using getDeclaredField()
163 Field field = cls.getDeclaredField(fieldName);
169 final Field field = cls.getDeclaredField(fieldName);
164170 if (!MemberUtils.isAccessible(field)) {
165171 if (forceAccess) {
166172 field.setAccessible(true);
169175 }
170176 }
171177 return field;
172 } catch (NoSuchFieldException e) { // NOPMD
178 } catch (final NoSuchFieldException e) { // NOPMD
173179 // ignore
174180 }
175181 return null;
176182 }
177183
178184 /**
179 * Reads an accessible static Field.
180 * @param field to read
185 * Gets all fields of the given class and its parents (if any).
186 *
187 * @param cls
188 * the {@link Class} to query
189 * @return an array of Fields (possibly empty).
190 * @throws IllegalArgumentException
191 * if the class is {@code null}
192 * @since 3.2
193 */
194 public static Field[] getAllFields(Class<?> cls) {
195 final List<Field> allFieldsList = getAllFieldsList(cls);
196 return allFieldsList.toArray(new Field[allFieldsList.size()]);
197 }
198
199 /**
200 * Gets all fields of the given class and its parents (if any).
201 *
202 * @param cls
203 * the {@link Class} to query
204 * @return an array of Fields (possibly empty).
205 * @throws IllegalArgumentException
206 * if the class is {@code null}
207 * @since 3.2
208 */
209 public static List<Field> getAllFieldsList(Class<?> cls) {
210 Validate.isTrue(cls != null, "The class must not be null");
211 final List<Field> allFields = new ArrayList<Field>();
212 Class<?> currentClass = cls;
213 while (currentClass != null) {
214 final Field[] declaredFields = currentClass.getDeclaredFields();
215 for (Field field : declaredFields) {
216 allFields.add(field);
217 }
218 currentClass = currentClass.getSuperclass();
219 }
220 return allFields;
221 }
222
223 /**
224 * Reads an accessible {@code static} {@link Field}.
225 *
226 * @param field
227 * to read
181228 * @return the field value
182 * @throws IllegalArgumentException if the field is null or not static
183 * @throws IllegalAccessException if the field is not accessible
184 */
185 public static Object readStaticField(Field field) throws IllegalAccessException {
229 * @throws IllegalArgumentException
230 * if the field is {@code null}, or not {@code static}
231 * @throws IllegalAccessException
232 * if the field is not accessible
233 */
234 public static Object readStaticField(final Field field) throws IllegalAccessException {
186235 return readStaticField(field, false);
187236 }
188237
189238 /**
190 * Reads a static Field.
191 * @param field to read
192 * @param forceAccess whether to break scope restrictions using the
193 * <code>setAccessible</code> method.
239 * Reads a static {@link Field}.
240 *
241 * @param field
242 * to read
243 * @param forceAccess
244 * whether to break scope restrictions using the
245 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
194246 * @return the field value
195 * @throws IllegalArgumentException if the field is null or not static
196 * @throws IllegalAccessException if the field is not made accessible
197 */
198 public static Object readStaticField(Field field, boolean forceAccess) throws IllegalAccessException {
199 if (field == null) {
200 throw new IllegalArgumentException("The field must not be null");
201 }
202 if (!Modifier.isStatic(field.getModifiers())) {
203 throw new IllegalArgumentException("The field '" + field.getName() + "' is not static");
204 }
247 * @throws IllegalArgumentException
248 * if the field is {@code null} or not {@code static}
249 * @throws IllegalAccessException
250 * if the field is not made accessible
251 */
252 public static Object readStaticField(final Field field, final boolean forceAccess) throws IllegalAccessException {
253 Validate.isTrue(field != null, "The field must not be null");
254 Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field '%s' is not static", field.getName());
205255 return readField(field, (Object) null, forceAccess);
206256 }
207257
208258 /**
209 * Reads the named public static field. Superclasses will be considered.
210 * @param cls the class to reflect, must not be null
211 * @param fieldName the field name to obtain
259 * Reads the named {@code public static} {@link Field}. Superclasses will be considered.
260 *
261 * @param cls
262 * the {@link Class} to reflect, must not be {@code null}
263 * @param fieldName
264 * the field name to obtain
212265 * @return the value of the field
213 * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found
214 * @throws IllegalAccessException if the field is not accessible
215 */
216 public static Object readStaticField(Class<?> cls, String fieldName) throws IllegalAccessException {
266 * @throws IllegalArgumentException
267 * if the class is {@code null}, or the field name is blank or empty,
268 * is not {@code static}, or could not be found
269 * @throws IllegalAccessException
270 * if the field is not accessible
271 */
272 public static Object readStaticField(final Class<?> cls, final String fieldName) throws IllegalAccessException {
217273 return readStaticField(cls, fieldName, false);
218274 }
219275
220276 /**
221 * Reads the named static field. Superclasses will be considered.
222 * @param cls the class to reflect, must not be null
223 * @param fieldName the field name to obtain
224 * @param forceAccess whether to break scope restrictions using the
225 * <code>setAccessible</code> method. <code>False</code> will only
226 * match public fields.
277 * Reads the named {@code static} {@link Field}. Superclasses will be considered.
278 *
279 * @param cls
280 * the {@link Class} to reflect, must not be {@code null}
281 * @param fieldName
282 * the field name to obtain
283 * @param forceAccess
284 * whether to break scope restrictions using the
285 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
286 * {@code false} will only match {@code public} fields.
227287 * @return the Field object
228 * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found
229 * @throws IllegalAccessException if the field is not made accessible
230 */
231 public static Object readStaticField(Class<?> cls, String fieldName, boolean forceAccess)
232 throws IllegalAccessException {
233 Field field = getField(cls, fieldName, forceAccess);
234 if (field == null) {
235 throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls);
236 }
237 //already forced access above, don't repeat it here:
288 * @throws IllegalArgumentException
289 * if the class is {@code null}, or the field name is blank or empty,
290 * is not {@code static}, or could not be found
291 * @throws IllegalAccessException
292 * if the field is not made accessible
293 */
294 public static Object readStaticField(final Class<?> cls, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
295 final Field field = getField(cls, fieldName, forceAccess);
296 Validate.isTrue(field != null, "Cannot locate field '%s' on %s", fieldName, cls);
297 // already forced access above, don't repeat it here:
238298 return readStaticField(field, false);
239299 }
240300
241301 /**
242 * Gets a static Field value by name. The field must be public.
302 * Gets the value of a {@code static} {@link Field} by name. The field must be {@code public}.
243303 * Only the specified class will be considered.
244 *
245 * @param cls the class to reflect, must not be null
246 * @param fieldName the field name to obtain
304 *
305 * @param cls
306 * the {@link Class} to reflect, must not be {@code null}
307 * @param fieldName
308 * the field name to obtain
247309 * @return the value of the field
248 * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found
249 * @throws IllegalAccessException if the field is not accessible
250 */
251 public static Object readDeclaredStaticField(Class<?> cls, String fieldName) throws IllegalAccessException {
310 * @throws IllegalArgumentException
311 * if the class is {@code null}, or the field name is blank or empty,
312 * is not {@code static}, or could not be found
313 * @throws IllegalAccessException
314 * if the field is not accessible
315 */
316 public static Object readDeclaredStaticField(final Class<?> cls, final String fieldName) throws IllegalAccessException {
252317 return readDeclaredStaticField(cls, fieldName, false);
253318 }
254319
255320 /**
256 * Gets a static Field value by name. Only the specified class will
257 * be considered.
258 *
259 * @param cls the class to reflect, must not be null
260 * @param fieldName the field name to obtain
261 * @param forceAccess whether to break scope restrictions using the
262 * <code>setAccessible</code> method. <code>False</code> will only
263 * match public fields.
321 * Gets the value of a {@code static} {@link Field} by name.
322 * Only the specified class will be considered.
323 *
324 * @param cls
325 * the {@link Class} to reflect, must not be {@code null}
326 * @param fieldName
327 * the field name to obtain
328 * @param forceAccess
329 * whether to break scope restrictions using the
330 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
331 * {@code false} will only match {@code public} fields.
264332 * @return the Field object
265 * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found
266 * @throws IllegalAccessException if the field is not made accessible
267 */
268 public static Object readDeclaredStaticField(Class<?> cls, String fieldName, boolean forceAccess)
269 throws IllegalAccessException {
270 Field field = getDeclaredField(cls, fieldName, forceAccess);
271 if (field == null) {
272 throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName);
273 }
274 //already forced access above, don't repeat it here:
333 * @throws IllegalArgumentException
334 * if the class is {@code null}, or the field name is blank or empty,
335 * is not {@code static}, or could not be found
336 * @throws IllegalAccessException
337 * if the field is not made accessible
338 */
339 public static Object readDeclaredStaticField(final Class<?> cls, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
340 final Field field = getDeclaredField(cls, fieldName, forceAccess);
341 Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
342 // already forced access above, don't repeat it here:
275343 return readStaticField(field, false);
276344 }
277345
278346 /**
279 * Reads an accessible Field.
280 * @param field the field to use
281 * @param target the object to call on, may be null for static fields
347 * Reads an accessible {@link Field}.
348 *
349 * @param field
350 * the field to use
351 * @param target
352 * the object to call on, may be {@code null} for {@code static} fields
282353 * @return the field value
283 * @throws IllegalArgumentException if the field is null
284 * @throws IllegalAccessException if the field is not accessible
285 */
286 public static Object readField(Field field, Object target) throws IllegalAccessException {
354 * @throws IllegalArgumentException
355 * if the field is {@code null}
356 * @throws IllegalAccessException
357 * if the field is not accessible
358 */
359 public static Object readField(final Field field, final Object target) throws IllegalAccessException {
287360 return readField(field, target, false);
288361 }
289362
290363 /**
291 * Reads a Field.
292 * @param field the field to use
293 * @param target the object to call on, may be null for static fields
294 * @param forceAccess whether to break scope restrictions using the
295 * <code>setAccessible</code> method.
364 * Reads a {@link Field}.
365 *
366 * @param field
367 * the field to use
368 * @param target
369 * the object to call on, may be {@code null} for {@code static} fields
370 * @param forceAccess
371 * whether to break scope restrictions using the
372 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
296373 * @return the field value
297 * @throws IllegalArgumentException if the field is null
298 * @throws IllegalAccessException if the field is not made accessible
299 */
300 public static Object readField(Field field, Object target, boolean forceAccess) throws IllegalAccessException {
301 if (field == null) {
302 throw new IllegalArgumentException("The field must not be null");
303 }
374 * @throws IllegalArgumentException
375 * if the field is {@code null}
376 * @throws IllegalAccessException
377 * if the field is not made accessible
378 */
379 public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException {
380 Validate.isTrue(field != null, "The field must not be null");
304381 if (forceAccess && !field.isAccessible()) {
305382 field.setAccessible(true);
306383 } else {
310387 }
311388
312389 /**
313 * Reads the named public field. Superclasses will be considered.
314 * @param target the object to reflect, must not be null
315 * @param fieldName the field name to obtain
390 * Reads the named {@code public} {@link Field}. Superclasses will be considered.
391 *
392 * @param target
393 * the object to reflect, must not be {@code null}
394 * @param fieldName
395 * the field name to obtain
316396 * @return the value of the field
317 * @throws IllegalArgumentException if the class or field name is null
318 * @throws IllegalAccessException if the named field is not public
319 */
320 public static Object readField(Object target, String fieldName) throws IllegalAccessException {
397 * @throws IllegalArgumentException
398 * if the class is {@code null}, or
399 * the field name is blank or empty or could not be found
400 * @throws IllegalAccessException
401 * if the named field is not {@code public}
402 */
403 public static Object readField(final Object target, final String fieldName) throws IllegalAccessException {
321404 return readField(target, fieldName, false);
322405 }
323406
324407 /**
325 * Reads the named field. Superclasses will be considered.
326 * @param target the object to reflect, must not be null
327 * @param fieldName the field name to obtain
328 * @param forceAccess whether to break scope restrictions using the
329 * <code>setAccessible</code> method. <code>False</code> will only
330 * match public fields.
408 * Reads the named {@link Field}. Superclasses will be considered.
409 *
410 * @param target
411 * the object to reflect, must not be {@code null}
412 * @param fieldName
413 * the field name to obtain
414 * @param forceAccess
415 * whether to break scope restrictions using the
416 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
417 * {@code false} will only match {@code public} fields.
331418 * @return the field value
332 * @throws IllegalArgumentException if the class or field name is null
333 * @throws IllegalAccessException if the named field is not made accessible
334 */
335 public static Object readField(Object target, String fieldName, boolean forceAccess) throws IllegalAccessException {
336 if (target == null) {
337 throw new IllegalArgumentException("target object must not be null");
338 }
339 Class<?> cls = target.getClass();
340 Field field = getField(cls, fieldName, forceAccess);
341 if (field == null) {
342 throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls);
343 }
344 //already forced access above, don't repeat it here:
419 * @throws IllegalArgumentException
420 * if {@code target} is {@code null}, or
421 * the field name is blank or empty or could not be found
422 * @throws IllegalAccessException
423 * if the named field is not made accessible
424 */
425 public static Object readField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
426 Validate.isTrue(target != null, "target object must not be null");
427 final Class<?> cls = target.getClass();
428 final Field field = getField(cls, fieldName, forceAccess);
429 Validate.isTrue(field != null, "Cannot locate field %s on %s" , fieldName, cls);
430 // already forced access above, don't repeat it here:
345431 return readField(field, target);
346432 }
347433
348434 /**
349 * Reads the named public field. Only the class of the specified object will be considered.
350 * @param target the object to reflect, must not be null
351 * @param fieldName the field name to obtain
435 * Reads the named {@code public} {@link Field}. Only the class of the specified object will be considered.
436 *
437 * @param target
438 * the object to reflect, must not be {@code null}
439 * @param fieldName
440 * the field name to obtain
352441 * @return the value of the field
353 * @throws IllegalArgumentException if the class or field name is null
354 * @throws IllegalAccessException if the named field is not public
355 */
356 public static Object readDeclaredField(Object target, String fieldName) throws IllegalAccessException {
442 * @throws IllegalArgumentException
443 * if {@code target} is {@code null}, or
444 * the field name is blank or empty or could not be found
445 * @throws IllegalAccessException
446 * if the named field is not {@code public}
447 */
448 public static Object readDeclaredField(final Object target, final String fieldName) throws IllegalAccessException {
357449 return readDeclaredField(target, fieldName, false);
358450 }
359451
360452 /**
361 * <p<>Gets a Field value by name. Only the class of the specified
362 * object will be considered.
363 *
364 * @param target the object to reflect, must not be null
365 * @param fieldName the field name to obtain
366 * @param forceAccess whether to break scope restrictions using the
367 * <code>setAccessible</code> method. <code>False</code> will only
368 * match public fields.
453 * <p<>Gets a {@link Field} value by name. Only the class of the specified object will be considered.
454 *
455 * @param target
456 * the object to reflect, must not be {@code null}
457 * @param fieldName
458 * the field name to obtain
459 * @param forceAccess
460 * whether to break scope restrictions using the
461 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
462 * {@code false} will only match public fields.
369463 * @return the Field object
370 * @throws IllegalArgumentException if <code>target</code> or <code>fieldName</code> is null
371 * @throws IllegalAccessException if the field is not made accessible
372 */
373 public static Object readDeclaredField(Object target, String fieldName, boolean forceAccess)
374 throws IllegalAccessException {
375 if (target == null) {
376 throw new IllegalArgumentException("target object must not be null");
377 }
378 Class<?> cls = target.getClass();
379 Field field = getDeclaredField(cls, fieldName, forceAccess);
380 if (field == null) {
381 throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName);
382 }
383 //already forced access above, don't repeat it here:
464 * @throws IllegalArgumentException
465 * if {@code target} is {@code null}, or
466 * the field name is blank or empty or could not be found
467 * @throws IllegalAccessException
468 * if the field is not made accessible
469 */
470 public static Object readDeclaredField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
471 Validate.isTrue(target != null, "target object must not be null");
472 final Class<?> cls = target.getClass();
473 final Field field = getDeclaredField(cls, fieldName, forceAccess);
474 Validate.isTrue(field != null, "Cannot locate declared field %s.%s" , cls, fieldName);
475 // already forced access above, don't repeat it here:
384476 return readField(field, target);
385477 }
386478
387479 /**
388 * Writes a public static Field.
389 * @param field to write
390 * @param value to set
391 * @throws IllegalArgumentException if the field is null or not static
392 * @throws IllegalAccessException if the field is not public or is final
393 */
394 public static void writeStaticField(Field field, Object value) throws IllegalAccessException {
480 * Writes a {@code public static} {@link Field}.
481 *
482 * @param field
483 * to write
484 * @param value
485 * to set
486 * @throws IllegalArgumentException
487 * if the field is {@code null} or not {@code static},
488 * or {@code value} is not assignable
489 * @throws IllegalAccessException
490 * if the field is not {@code public} or is {@code final}
491 */
492 public static void writeStaticField(final Field field, final Object value) throws IllegalAccessException {
395493 writeStaticField(field, value, false);
396494 }
397495
398496 /**
399 * Writes a static Field.
400 * @param field to write
401 * @param value to set
402 * @param forceAccess whether to break scope restrictions using the
403 * <code>setAccessible</code> method. <code>False</code> will only
404 * match public fields.
405 * @throws IllegalArgumentException if the field is null or not static
406 * @throws IllegalAccessException if the field is not made accessible or is final
407 */
408 public static void writeStaticField(Field field, Object value, boolean forceAccess) throws IllegalAccessException {
409 if (field == null) {
410 throw new IllegalArgumentException("The field must not be null");
411 }
412 if (!Modifier.isStatic(field.getModifiers())) {
413 throw new IllegalArgumentException("The field '" + field.getName() + "' is not static");
414 }
497 * Writes a static {@link Field}.
498 *
499 * @param field
500 * to write
501 * @param value
502 * to set
503 * @param forceAccess
504 * whether to break scope restrictions using the
505 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false}
506 * will only match {@code public} fields.
507 * @throws IllegalArgumentException
508 * if the field is {@code null} or not {@code static},
509 * or {@code value} is not assignable
510 * @throws IllegalAccessException
511 * if the field is not made accessible or is {@code final}
512 */
513 public static void writeStaticField(final Field field, final Object value, final boolean forceAccess) throws IllegalAccessException {
514 Validate.isTrue(field != null, "The field must not be null");
515 Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field %s.%s is not static",
516 field.getDeclaringClass().getName(), field.getName());
415517 writeField(field, (Object) null, value, forceAccess);
416518 }
417519
418520 /**
419 * Writes a named public static Field. Superclasses will be considered.
420 * @param cls Class on which the Field is to be found
421 * @param fieldName to write
422 * @param value to set
423 * @throws IllegalArgumentException if the field cannot be located or is not static
424 * @throws IllegalAccessException if the field is not public or is final
425 */
426 public static void writeStaticField(Class<?> cls, String fieldName, Object value) throws IllegalAccessException {
521 * Writes a named {@code public static} {@link Field}. Superclasses will be considered.
522 *
523 * @param cls
524 * {@link Class} on which the field is to be found
525 * @param fieldName
526 * to write
527 * @param value
528 * to set
529 * @throws IllegalArgumentException
530 * if {@code cls} is {@code null},
531 * the field name is blank or empty,
532 * the field cannot be located or is not {@code static}, or
533 * {@code value} is not assignable
534 * @throws IllegalAccessException
535 * if the field is not {@code public} or is {@code final}
536 */
537 public static void writeStaticField(final Class<?> cls, final String fieldName, final Object value) throws IllegalAccessException {
427538 writeStaticField(cls, fieldName, value, false);
428539 }
429540
430541 /**
431 * Writes a named static Field. Superclasses will be considered.
432 * @param cls Class on which the Field is to be found
433 * @param fieldName to write
434 * @param value to set
435 * @param forceAccess whether to break scope restrictions using the
436 * <code>setAccessible</code> method. <code>False</code> will only
437 * match public fields.
438 * @throws IllegalArgumentException if the field cannot be located or is not static
439 * @throws IllegalAccessException if the field is not made accessible or is final
440 */
441 public static void writeStaticField(Class<?> cls, String fieldName, Object value, boolean forceAccess)
542 * Writes a named {@code static} {@link Field}. Superclasses will be considered.
543 *
544 * @param cls
545 * {@link Class} on which the field is to be found
546 * @param fieldName
547 * to write
548 * @param value
549 * to set
550 * @param forceAccess
551 * whether to break scope restrictions using the
552 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
553 * {@code false} will only match {@code public} fields.
554 * @throws IllegalArgumentException
555 * if {@code cls} is {@code null},
556 * the field name is blank or empty,
557 * the field cannot be located or is not {@code static}, or
558 * {@code value} is not assignable
559 * @throws IllegalAccessException
560 * if the field is not made accessible or is {@code final}
561 */
562 public static void writeStaticField(final Class<?> cls, final String fieldName, final Object value, final boolean forceAccess)
442563 throws IllegalAccessException {
443 Field field = getField(cls, fieldName, forceAccess);
444 if (field == null) {
445 throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls);
446 }
447 //already forced access above, don't repeat it here:
564 final Field field = getField(cls, fieldName, forceAccess);
565 Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls);
566 // already forced access above, don't repeat it here:
448567 writeStaticField(field, value);
449568 }
450569
451570 /**
452 * Writes a named public static Field. Only the specified class will be considered.
453 * @param cls Class on which the Field is to be found
454 * @param fieldName to write
455 * @param value to set
456 * @throws IllegalArgumentException if the field cannot be located or is not static
457 * @throws IllegalAccessException if the field is not public or is final
458 */
459 public static void writeDeclaredStaticField(Class<?> cls, String fieldName, Object value)
571 * Writes a named {@code public static} {@link Field}. Only the specified class will be considered.
572 *
573 * @param cls
574 * {@link Class} on which the field is to be found
575 * @param fieldName
576 * to write
577 * @param value
578 * to set
579 * @throws IllegalArgumentException
580 * if {@code cls} is {@code null},
581 * the field name is blank or empty,
582 * the field cannot be located or is not {@code static}, or
583 * {@code value} is not assignable
584 * @throws IllegalAccessException
585 * if the field is not {@code public} or is {@code final}
586 */
587 public static void writeDeclaredStaticField(final Class<?> cls, final String fieldName, final Object value) throws IllegalAccessException {
588 writeDeclaredStaticField(cls, fieldName, value, false);
589 }
590
591 /**
592 * Writes a named {@code static} {@link Field}. Only the specified class will be considered.
593 *
594 * @param cls
595 * {@link Class} on which the field is to be found
596 * @param fieldName
597 * to write
598 * @param value
599 * to set
600 * @param forceAccess
601 * whether to break scope restrictions using the {@code AccessibleObject#setAccessible(boolean)} method.
602 * {@code false} will only match {@code public} fields.
603 * @throws IllegalArgumentException
604 * if {@code cls} is {@code null},
605 * the field name is blank or empty,
606 * the field cannot be located or is not {@code static}, or
607 * {@code value} is not assignable
608 * @throws IllegalAccessException
609 * if the field is not made accessible or is {@code final}
610 */
611 public static void writeDeclaredStaticField(final Class<?> cls, final String fieldName, final Object value, final boolean forceAccess)
460612 throws IllegalAccessException {
461 writeDeclaredStaticField(cls, fieldName, value, false);
462 }
463
464 /**
465 * Writes a named static Field. Only the specified class will be considered.
466 * @param cls Class on which the Field is to be found
467 * @param fieldName to write
468 * @param value to set
469 * @param forceAccess whether to break scope restrictions using the
470 * <code>setAccessible</code> method. <code>False</code> will only
471 * match public fields.
472 * @throws IllegalArgumentException if the field cannot be located or is not static
473 * @throws IllegalAccessException if the field is not made accessible or is final
474 */
475 public static void writeDeclaredStaticField(Class<?> cls, String fieldName, Object value, boolean forceAccess)
613 final Field field = getDeclaredField(cls, fieldName, forceAccess);
614 Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
615 // already forced access above, don't repeat it here:
616 writeField(field, (Object) null, value);
617 }
618
619 /**
620 * Writes an accessible {@link Field}.
621 *
622 * @param field
623 * to write
624 * @param target
625 * the object to call on, may be {@code null} for {@code static} fields
626 * @param value
627 * to set
628 * @throws IllegalAccessException
629 * if the field or target is {@code null},
630 * the field is not accessible or is {@code final}, or
631 * {@code value} is not assignable
632 */
633 public static void writeField(final Field field, final Object target, final Object value) throws IllegalAccessException {
634 writeField(field, target, value, false);
635 }
636
637 /**
638 * Writes a {@link Field}.
639 *
640 * @param field
641 * to write
642 * @param target
643 * the object to call on, may be {@code null} for {@code static} fields
644 * @param value
645 * to set
646 * @param forceAccess
647 * whether to break scope restrictions using the
648 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
649 * {@code false} will only match {@code public} fields.
650 * @throws IllegalArgumentException
651 * if the field is {@code null} or
652 * {@code value} is not assignable
653 * @throws IllegalAccessException
654 * if the field is not made accessible or is {@code final}
655 */
656 public static void writeField(final Field field, final Object target, final Object value, final boolean forceAccess)
476657 throws IllegalAccessException {
477 Field field = getDeclaredField(cls, fieldName, forceAccess);
478 if (field == null) {
479 throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName);
480 }
481 //already forced access above, don't repeat it here:
482 writeField(field, (Object) null, value);
483 }
484
485 /**
486 * Writes an accessible field.
487 * @param field to write
488 * @param target the object to call on, may be null for static fields
489 * @param value to set
490 * @throws IllegalArgumentException if the field is null
491 * @throws IllegalAccessException if the field is not accessible or is final
492 */
493 public static void writeField(Field field, Object target, Object value) throws IllegalAccessException {
494 writeField(field, target, value, false);
495 }
496
497 /**
498 * Writes a field.
499 * @param field to write
500 * @param target the object to call on, may be null for static fields
501 * @param value to set
502 * @param forceAccess whether to break scope restrictions using the
503 * <code>setAccessible</code> method. <code>False</code> will only
504 * match public fields.
505 * @throws IllegalArgumentException if the field is null
506 * @throws IllegalAccessException if the field is not made accessible or is final
507 */
508 public static void writeField(Field field, Object target, Object value, boolean forceAccess)
509 throws IllegalAccessException {
510 if (field == null) {
511 throw new IllegalArgumentException("The field must not be null");
512 }
658 Validate.isTrue(field != null, "The field must not be null");
513659 if (forceAccess && !field.isAccessible()) {
514660 field.setAccessible(true);
515661 } else {
519665 }
520666
521667 /**
522 * Writes a public field. Superclasses will be considered.
523 * @param target the object to reflect, must not be null
524 * @param fieldName the field name to obtain
525 * @param value to set
526 * @throws IllegalArgumentException if <code>target</code> or <code>fieldName</code> is null
527 * @throws IllegalAccessException if the field is not accessible
528 */
529 public static void writeField(Object target, String fieldName, Object value) throws IllegalAccessException {
668 * Remove the final modifier from a {@link Field}
669 * @param field to remove the final modifier
670 * @throws IllegalArgumentException
671 * if the field is {@code null}
672 */
673 public static void removeFinalModifier(Field field) {
674 Validate.isTrue(field != null, "The field must not be null");
675
676 try {
677 if(Modifier.isFinal(field.getModifiers())){
678 Field modifiersField = Field.class.getDeclaredField("modifiers");
679 modifiersField.setAccessible(true);
680 modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
681 }
682 } catch (NoSuchFieldException ignored) {
683 // The field class contains always a modifiers field
684 } catch (IllegalAccessException ignored) {
685 // The modifiers field is made accessible
686 }
687 }
688
689 /**
690 * Writes a {@code public} {@link Field}. Superclasses will be considered.
691 *
692 * @param target
693 * the object to reflect, must not be {@code null}
694 * @param fieldName
695 * the field name to obtain
696 * @param value
697 * to set
698 * @throws IllegalArgumentException
699 * if {@code target} is {@code null},
700 * {@code fieldName} is blank or empty or could not be found,
701 * or {@code value} is not assignable
702 * @throws IllegalAccessException
703 * if the field is not accessible
704 */
705 public static void writeField(final Object target, final String fieldName, final Object value) throws IllegalAccessException {
530706 writeField(target, fieldName, value, false);
531707 }
532708
533709 /**
534 * Writes a field. Superclasses will be considered.
535 * @param target the object to reflect, must not be null
536 * @param fieldName the field name to obtain
537 * @param value to set
538 * @param forceAccess whether to break scope restrictions using the
539 * <code>setAccessible</code> method. <code>False</code> will only
540 * match public fields.
541 * @throws IllegalArgumentException if <code>target</code> or <code>fieldName</code> is null
542 * @throws IllegalAccessException if the field is not made accessible
543 */
544 public static void writeField(Object target, String fieldName, Object value, boolean forceAccess)
710 * Writes a {@link Field}. Superclasses will be considered.
711 *
712 * @param target
713 * the object to reflect, must not be {@code null}
714 * @param fieldName
715 * the field name to obtain
716 * @param value
717 * to set
718 * @param forceAccess
719 * whether to break scope restrictions using the
720 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false}
721 * will only match {@code public} fields.
722 * @throws IllegalArgumentException
723 * if {@code target} is {@code null},
724 * {@code fieldName} is blank or empty or could not be found,
725 * or {@code value} is not assignable
726 * @throws IllegalAccessException
727 * if the field is not made accessible
728 */
729 public static void writeField(final Object target, final String fieldName, final Object value, final boolean forceAccess)
545730 throws IllegalAccessException {
546 if (target == null) {
547 throw new IllegalArgumentException("target object must not be null");
548 }
549 Class<?> cls = target.getClass();
550 Field field = getField(cls, fieldName, forceAccess);
551 if (field == null) {
552 throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName);
553 }
554 //already forced access above, don't repeat it here:
731 Validate.isTrue(target != null, "target object must not be null");
732 final Class<?> cls = target.getClass();
733 final Field field = getField(cls, fieldName, forceAccess);
734 Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
735 // already forced access above, don't repeat it here:
555736 writeField(field, target, value);
556737 }
557738
558739 /**
559 * Writes a public field. Only the specified class will be considered.
560 * @param target the object to reflect, must not be null
561 * @param fieldName the field name to obtain
562 * @param value to set
563 * @throws IllegalArgumentException if <code>target</code> or <code>fieldName</code> is null
564 * @throws IllegalAccessException if the field is not made accessible
565 */
566 public static void writeDeclaredField(Object target, String fieldName, Object value) throws IllegalAccessException {
740 * Writes a {@code public} {@link Field}. Only the specified class will be considered.
741 *
742 * @param target
743 * the object to reflect, must not be {@code null}
744 * @param fieldName
745 * the field name to obtain
746 * @param value
747 * to set
748 * @throws IllegalArgumentException
749 * if {@code target} is {@code null},
750 * {@code fieldName} is blank or empty or could not be found,
751 * or {@code value} is not assignable
752 * @throws IllegalAccessException
753 * if the field is not made accessible
754 */
755 public static void writeDeclaredField(final Object target, final String fieldName, final Object value) throws IllegalAccessException {
567756 writeDeclaredField(target, fieldName, value, false);
568757 }
569758
570759 /**
571 * Writes a public field. Only the specified class will be considered.
572 * @param target the object to reflect, must not be null
573 * @param fieldName the field name to obtain
574 * @param value to set
575 * @param forceAccess whether to break scope restrictions using the
576 * <code>setAccessible</code> method. <code>False</code> will only
577 * match public fields.
578 * @throws IllegalArgumentException if <code>target</code> or <code>fieldName</code> is null
579 * @throws IllegalAccessException if the field is not made accessible
580 */
581 public static void writeDeclaredField(Object target, String fieldName, Object value, boolean forceAccess)
760 * Writes a {@code public} {@link Field}. Only the specified class will be considered.
761 *
762 * @param target
763 * the object to reflect, must not be {@code null}
764 * @param fieldName
765 * the field name to obtain
766 * @param value
767 * to set
768 * @param forceAccess
769 * whether to break scope restrictions using the
770 * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
771 * {@code false} will only match {@code public} fields.
772 * @throws IllegalArgumentException
773 * if {@code target} is {@code null},
774 * {@code fieldName} is blank or empty or could not be found,
775 * or {@code value} is not assignable
776 * @throws IllegalAccessException
777 * if the field is not made accessible
778 */
779 public static void writeDeclaredField(final Object target, final String fieldName, final Object value, final boolean forceAccess)
582780 throws IllegalAccessException {
583 if (target == null) {
584 throw new IllegalArgumentException("target object must not be null");
585 }
586 Class<?> cls = target.getClass();
587 Field field = getDeclaredField(cls, fieldName, forceAccess);
588 if (field == null) {
589 throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName);
590 }
591 //already forced access above, don't repeat it here:
781 Validate.isTrue(target != null, "target object must not be null");
782 final Class<?> cls = target.getClass();
783 final Field field = getDeclaredField(cls, fieldName, forceAccess);
784 Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
785 // already forced access above, don't repeat it here:
592786 writeField(field, target, value);
593787 }
594788 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect;
17
18 import org.apache.commons.lang3.BooleanUtils;
19
20 /**
21 * <p>Utility methods focusing on inheritance.</p>
22 *
23 * @since 3.2
24 */
25 public class InheritanceUtils {
26
27 /**
28 * <p>{@link InheritanceUtils} instances should NOT be constructed in standard programming.
29 * Instead, the class should be used as
30 * {@code MethodUtils.getAccessibleMethod(method)}.</p>
31 *
32 * <p>This constructor is {@code public} to permit tools that require a JavaBean
33 * instance to operate.</p>
34 */
35 public InheritanceUtils() {
36 super();
37 }
38
39 /**
40 * <p>Returns the number of inheritance hops between two classes.</p>
41 *
42 * @param child the child class, may be {@code null}
43 * @param parent the parent class, may be {@code null}
44 * @return the number of generations between the child and parent; 0 if the same class;
45 * -1 if the classes are not related as child and parent (includes where either class is null)
46 * @since 3.2
47 */
48 public static int distance(final Class<?> child, final Class<?> parent) {
49 if (child == null || parent == null) {
50 return -1;
51 }
52
53 if (child.equals(parent)) {
54 return 0;
55 }
56
57 final Class<?> cParent = child.getSuperclass();
58 int d = BooleanUtils.toInteger(parent.equals(cParent));
59
60 if (d == 1) {
61 return d;
62 } else {
63 d += distance(cParent, parent);
64 return d > 0 ? d + 1 : -1;
65 }
66 }
67 }
2222 import org.apache.commons.lang3.ClassUtils;
2323
2424 /**
25 * Contains common code for working with Methods/Constructors, extracted and
26 * refactored from <code>MethodUtils</code> when it was imported from Commons
25 * Contains common code for working with {@link Method}s/{@link Constructor}s, extracted and
26 * refactored from {@link MethodUtils} when it was imported from Commons
2727 * BeanUtils.
2828 *
2929 * @since 2.5
30 * @version $Id: MemberUtils.java 1143537 2011-07-06 19:30:22Z joehni $
30 * @version $Id: MemberUtils.java 1531403 2013-10-11 19:38:49Z mbenson $
3131 */
3232 abstract class MemberUtils {
3333 // TODO extract an interface to implement compareParameterSets(...)?
4141 /**
4242 * XXX Default access superclass workaround
4343 *
44 * When a public class has a default access superclass with public members,
44 * When a {@code public} class has a default access superclass with {@code public} members,
4545 * these members are accessible. Calling them from compiled code works fine.
4646 * Unfortunately, on some JVMs, using reflection to invoke these members
47 * seems to (wrongly) prevent access even when the modifier is public.
48 * Calling setAccessible(true) solves the problem but will only work from
47 * seems to (wrongly) prevent access even when the modifier is {@code public}.
48 * Calling {@code setAccessible(true)} solves the problem but will only work from
4949 * sufficiently privileged code. Better workarounds would be gratefully
5050 * accepted.
5151 * @param o the AccessibleObject to set as accessible
5252 */
53 static void setAccessibleWorkaround(AccessibleObject o) {
53 static void setAccessibleWorkaround(final AccessibleObject o) {
5454 if (o == null || o.isAccessible()) {
5555 return;
5656 }
57 Member m = (Member) o;
57 final Member m = (Member) o;
5858 if (Modifier.isPublic(m.getModifiers())
5959 && isPackageAccess(m.getDeclaringClass().getModifiers())) {
6060 try {
6161 o.setAccessible(true);
62 } catch (SecurityException e) { // NOPMD
62 } catch (final SecurityException e) { // NOPMD
6363 // ignore in favor of subsequent IllegalAccessException
6464 }
6565 }
6868 /**
6969 * Returns whether a given set of modifiers implies package access.
7070 * @param modifiers to test
71 * @return true unless package/protected/private modifier detected
71 * @return {@code true} unless {@code package}/{@code protected}/{@code private} modifier detected
7272 */
73 static boolean isPackageAccess(int modifiers) {
73 static boolean isPackageAccess(final int modifiers) {
7474 return (modifiers & ACCESS_TEST) == 0;
7575 }
7676
7777 /**
78 * Returns whether a Member is accessible.
78 * Returns whether a {@link Member} is accessible.
7979 * @param m Member to check
80 * @return true if <code>m</code> is accessible
80 * @return {@code true} if <code>m</code> is accessible
8181 */
82 static boolean isAccessible(Member m) {
82 static boolean isAccessible(final Member m) {
8383 return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic();
8484 }
8585
9292 * @param left the "left" parameter set
9393 * @param right the "right" parameter set
9494 * @param actual the runtime parameter types to match against
95 * <code>left</code>/<code>right</code>
96 * @return int consistent with <code>compare</code> semantics
95 * {@code left}/{@code right}
96 * @return int consistent with {@code compare} semantics
9797 */
98 static int compareParameterTypes(Class<?>[] left, Class<?>[] right, Class<?>[] actual) {
99 float leftCost = getTotalTransformationCost(actual, left);
100 float rightCost = getTotalTransformationCost(actual, right);
98 static int compareParameterTypes(final Class<?>[] left, final Class<?>[] right, final Class<?>[] actual) {
99 final float leftCost = getTotalTransformationCost(actual, left);
100 final float rightCost = getTotalTransformationCost(actual, right);
101101 return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0;
102102 }
103103
108108 * @param destArgs The destination arguments
109109 * @return The total transformation cost
110110 */
111 private static float getTotalTransformationCost(Class<?>[] srcArgs, Class<?>[] destArgs) {
111 private static float getTotalTransformationCost(final Class<?>[] srcArgs, final Class<?>[] destArgs) {
112112 float totalCost = 0.0f;
113113 for (int i = 0; i < srcArgs.length; i++) {
114114 Class<?> srcClass, destClass;
127127 * @param destClass The destination class
128128 * @return The cost of transforming an object
129129 */
130 private static float getObjectTransformationCost(Class<?> srcClass, Class<?> destClass) {
130 private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) {
131131 if (destClass.isPrimitive()) {
132132 return getPrimitivePromotionCost(srcClass, destClass);
133133 }
1818 import java.lang.reflect.InvocationTargetException;
1919 import java.lang.reflect.Method;
2020 import java.lang.reflect.Modifier;
21 import java.lang.reflect.Type;
22 import java.lang.reflect.TypeVariable;
23 import java.util.Arrays;
24 import java.util.Iterator;
25 import java.util.LinkedHashSet;
26 import java.util.Map;
27 import java.util.Set;
2128
2229 import org.apache.commons.lang3.ArrayUtils;
2330 import org.apache.commons.lang3.ClassUtils;
31 import org.apache.commons.lang3.ClassUtils.Interfaces;
32 import org.apache.commons.lang3.Validate;
2433
2534 /**
26 * <p>Utility reflection methods focused on methods, originally from Commons BeanUtils.
35 * <p>Utility reflection methods focused on {@link Method}s, originally from Commons BeanUtils.
2736 * Differences from the BeanUtils version may be noted, especially where similar functionality
2837 * already existed within Lang.
2938 * </p>
3039 *
3140 * <h3>Known Limitations</h3>
3241 * <h4>Accessing Public Methods In A Default Access Superclass</h4>
33 * <p>There is an issue when invoking public methods contained in a default access superclass on JREs prior to 1.4.
34 * Reflection locates these methods fine and correctly assigns them as public.
35 * However, an <code>IllegalAccessException</code> is thrown if the method is invoked.</p>
42 * <p>There is an issue when invoking {@code public} methods contained in a default access superclass on JREs prior to 1.4.
43 * Reflection locates these methods fine and correctly assigns them as {@code public}.
44 * However, an {@link IllegalAccessException} is thrown if the method is invoked.</p>
3645 *
37 * <p><code>MethodUtils</code> contains a workaround for this situation.
38 * It will attempt to call <code>setAccessible</code> on this method.
46 * <p>{@link MethodUtils} contains a workaround for this situation.
47 * It will attempt to call {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} on this method.
3948 * If this call succeeds, then the method can be invoked as normal.
4049 * This call will only succeed when the application has sufficient security privileges.
4150 * If this call fails then the method may fail.</p>
4251 *
4352 * @since 2.5
44 * @version $Id: MethodUtils.java 1166253 2011-09-07 16:27:42Z ggregory $
53 * @version $Id: MethodUtils.java 1534831 2013-10-22 22:41:06Z mbenson $
4554 */
4655 public class MethodUtils {
4756
4857 /**
49 * <p>MethodUtils instances should NOT be constructed in standard programming.
58 * <p>{@link MethodUtils} instances should NOT be constructed in standard programming.
5059 * Instead, the class should be used as
51 * <code>MethodUtils.getAccessibleMethod(method)</code>.</p>
52 *
53 * <p>This constructor is public to permit tools that require a JavaBean
60 * {@code MethodUtils.getAccessibleMethod(method)}.</p>
61 *
62 * <p>This constructor is {@code public} to permit tools that require a JavaBean
5463 * instance to operate.</p>
5564 */
5665 public MethodUtils() {
6372 * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
6473 *
6574 * <p>This method supports calls to methods taking primitive parameters
66 * via passing in wrapping classes. So, for example, a <code>Boolean</code> object
67 * would match a <code>boolean</code> primitive.</p>
75 * via passing in wrapping classes. So, for example, a {@code Boolean} object
76 * would match a {@code boolean} primitive.</p>
6877 *
6978 * <p>This is a convenient wrapper for
7079 * {@link #invokeMethod(Object object,String methodName, Object[] args, Class[] parameterTypes)}.
7988 * @throws InvocationTargetException wraps an exception thrown by the method invoked
8089 * @throws IllegalAccessException if the requested method is not accessible via reflection
8190 */
82 public static Object invokeMethod(Object object, String methodName,
91 public static Object invokeMethod(final Object object, final String methodName,
8392 Object... args) throws NoSuchMethodException,
8493 IllegalAccessException, InvocationTargetException {
85 if (args == null) {
86 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
87 }
88 int arguments = args.length;
89 Class<?>[] parameterTypes = new Class[arguments];
90 for (int i = 0; i < arguments; i++) {
91 parameterTypes[i] = args[i].getClass();
92 }
94 args = ArrayUtils.nullToEmpty(args);
95 final Class<?>[] parameterTypes = ClassUtils.toClass(args);
9396 return invokeMethod(object, methodName, args, parameterTypes);
9497 }
9598
99102 * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
100103 *
101104 * <p>This method supports calls to methods taking primitive parameters
102 * via passing in wrapping classes. So, for example, a <code>Boolean</code> object
103 * would match a <code>boolean</code> primitive.</p>
105 * via passing in wrapping classes. So, for example, a {@code Boolean} object
106 * would match a {@code boolean} primitive.</p>
104107 *
105108 * @param object invoke method on this object
106109 * @param methodName get method with this name
112115 * @throws InvocationTargetException wraps an exception thrown by the method invoked
113116 * @throws IllegalAccessException if the requested method is not accessible via reflection
114117 */
115 public static Object invokeMethod(Object object, String methodName,
118 public static Object invokeMethod(final Object object, final String methodName,
116119 Object[] args, Class<?>[] parameterTypes)
117120 throws NoSuchMethodException, IllegalAccessException,
118121 InvocationTargetException {
119 if (parameterTypes == null) {
120 parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
121 }
122 if (args == null) {
123 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
124 }
125 Method method = getMatchingAccessibleMethod(object.getClass(),
122 parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
123 args = ArrayUtils.nullToEmpty(args);
124 final Method method = getMatchingAccessibleMethod(object.getClass(),
126125 methodName, parameterTypes);
127126 if (method == null) {
128127 throw new NoSuchMethodException("No such accessible method: "
137136 * types.</p>
138137 *
139138 * <p>This uses reflection to invoke the method obtained from a call to
140 * <code>getAccessibleMethod()</code>.</p>
139 * {@link #getAccessibleMethod}(Class,String,Class[])}.</p>
141140 *
142141 * @param object invoke method on this object
143142 * @param methodName get method with this name
144 * @param args use these arguments - treat null as empty array
143 * @param args use these arguments - treat {@code null} as empty array
145144 * @return The value returned by the invoked method
146145 *
147146 * @throws NoSuchMethodException if there is no such accessible method
150149 * @throws IllegalAccessException if the requested method is not accessible
151150 * via reflection
152151 */
153 public static Object invokeExactMethod(Object object, String methodName,
152 public static Object invokeExactMethod(final Object object, final String methodName,
154153 Object... args) throws NoSuchMethodException,
155154 IllegalAccessException, InvocationTargetException {
156 if (args == null) {
157 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
158 }
159 int arguments = args.length;
160 Class<?>[] parameterTypes = new Class[arguments];
161 for (int i = 0; i < arguments; i++) {
162 parameterTypes[i] = args[i].getClass();
163 }
155 args = ArrayUtils.nullToEmpty(args);
156 final Class<?>[] parameterTypes = ClassUtils.toClass(args);
164157 return invokeExactMethod(object, methodName, args, parameterTypes);
165158 }
166159
169162 * types given.</p>
170163 *
171164 * <p>This uses reflection to invoke the method obtained from a call to
172 * <code>getAccessibleMethod()</code>.</p>
165 * {@link #getAccessibleMethod(Class,String,Class[])}.</p>
173166 *
174167 * @param object invoke method on this object
175168 * @param methodName get method with this name
176169 * @param args use these arguments - treat null as empty array
177 * @param parameterTypes match these parameters - treat null as empty array
170 * @param parameterTypes match these parameters - treat {@code null} as empty array
178171 * @return The value returned by the invoked method
179172 *
180173 * @throws NoSuchMethodException if there is no such accessible method
183176 * @throws IllegalAccessException if the requested method is not accessible
184177 * via reflection
185178 */
186 public static Object invokeExactMethod(Object object, String methodName,
179 public static Object invokeExactMethod(final Object object, final String methodName,
187180 Object[] args, Class<?>[] parameterTypes)
188181 throws NoSuchMethodException, IllegalAccessException,
189182 InvocationTargetException {
190 if (args == null) {
191 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
192 }
193 if (parameterTypes == null) {
194 parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
195 }
196 Method method = getAccessibleMethod(object.getClass(), methodName,
183 args = ArrayUtils.nullToEmpty(args);
184 parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
185 final Method method = getAccessibleMethod(object.getClass(), methodName,
197186 parameterTypes);
198187 if (method == null) {
199188 throw new NoSuchMethodException("No such accessible method: "
204193 }
205194
206195 /**
207 * <p>Invokes a static method whose parameter types match exactly the parameter
196 * <p>Invokes a {@code static} method whose parameter types match exactly the parameter
208197 * types given.</p>
209198 *
210199 * <p>This uses reflection to invoke the method obtained from a call to
212201 *
213202 * @param cls invoke static method on this class
214203 * @param methodName get method with this name
215 * @param args use these arguments - treat null as empty array
216 * @param parameterTypes match these parameters - treat null as empty array
204 * @param args use these arguments - treat {@code null} as empty array
205 * @param parameterTypes match these parameters - treat {@code null} as empty array
217206 * @return The value returned by the invoked method
218207 *
219208 * @throws NoSuchMethodException if there is no such accessible method
222211 * @throws IllegalAccessException if the requested method is not accessible
223212 * via reflection
224213 */
225 public static Object invokeExactStaticMethod(Class<?> cls, String methodName,
214 public static Object invokeExactStaticMethod(final Class<?> cls, final String methodName,
226215 Object[] args, Class<?>[] parameterTypes)
227216 throws NoSuchMethodException, IllegalAccessException,
228217 InvocationTargetException {
229 if (args == null) {
230 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
231 }
232 if (parameterTypes == null) {
233 parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
234 }
235 Method method = getAccessibleMethod(cls, methodName, parameterTypes);
218 args = ArrayUtils.nullToEmpty(args);
219 parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
220 final Method method = getAccessibleMethod(cls, methodName, parameterTypes);
236221 if (method == null) {
237222 throw new NoSuchMethodException("No such accessible method: "
238223 + methodName + "() on class: " + cls.getName());
241226 }
242227
243228 /**
244 * <p>Invokes a named static method whose parameter type matches the object type.</p>
229 * <p>Invokes a named {@code static} method whose parameter type matches the object type.</p>
245230 *
246231 * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
247232 *
248233 * <p>This method supports calls to methods taking primitive parameters
249 * via passing in wrapping classes. So, for example, a <code>Boolean</code> class
250 * would match a <code>boolean</code> primitive.</p>
234 * via passing in wrapping classes. So, for example, a {@code Boolean} class
235 * would match a {@code boolean} primitive.</p>
251236 *
252237 * <p>This is a convenient wrapper for
253 * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}.
238 * {@link #invokeStaticMethod(Class, String, Object[], Class[])}.
254239 * </p>
255240 *
256241 * @param cls invoke static method on this class
257242 * @param methodName get method with this name
258 * @param args use these arguments - treat null as empty array
243 * @param args use these arguments - treat {@code null} as empty array
259244 * @return The value returned by the invoked method
260245 *
261246 * @throws NoSuchMethodException if there is no such accessible method
264249 * @throws IllegalAccessException if the requested method is not accessible
265250 * via reflection
266251 */
267 public static Object invokeStaticMethod(Class<?> cls, String methodName,
252 public static Object invokeStaticMethod(final Class<?> cls, final String methodName,
268253 Object... args) throws NoSuchMethodException,
269254 IllegalAccessException, InvocationTargetException {
270 if (args == null) {
271 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
272 }
273 int arguments = args.length;
274 Class<?>[] parameterTypes = new Class[arguments];
275 for (int i = 0; i < arguments; i++) {
276 parameterTypes[i] = args[i].getClass();
277 }
255 args = ArrayUtils.nullToEmpty(args);
256 final Class<?>[] parameterTypes = ClassUtils.toClass(args);
278257 return invokeStaticMethod(cls, methodName, args, parameterTypes);
279258 }
280259
281260 /**
282 * <p>Invokes a named static method whose parameter type matches the object type.</p>
261 * <p>Invokes a named {@code static} method whose parameter type matches the object type.</p>
283262 *
284263 * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
285264 *
286265 * <p>This method supports calls to methods taking primitive parameters
287 * via passing in wrapping classes. So, for example, a <code>Boolean</code> class
288 * would match a <code>boolean</code> primitive.</p>
266 * via passing in wrapping classes. So, for example, a {@code Boolean} class
267 * would match a {@code boolean} primitive.</p>
289268 *
290269 *
291270 * @param cls invoke static method on this class
292271 * @param methodName get method with this name
293 * @param args use these arguments - treat null as empty array
294 * @param parameterTypes match these parameters - treat null as empty array
272 * @param args use these arguments - treat {@code null} as empty array
273 * @param parameterTypes match these parameters - treat {@code null} as empty array
295274 * @return The value returned by the invoked method
296275 *
297276 * @throws NoSuchMethodException if there is no such accessible method
300279 * @throws IllegalAccessException if the requested method is not accessible
301280 * via reflection
302281 */
303 public static Object invokeStaticMethod(Class<?> cls, String methodName,
282 public static Object invokeStaticMethod(final Class<?> cls, final String methodName,
304283 Object[] args, Class<?>[] parameterTypes)
305284 throws NoSuchMethodException, IllegalAccessException,
306285 InvocationTargetException {
307 if (parameterTypes == null) {
308 parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
309 }
310 if (args == null) {
311 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
312 }
313 Method method = getMatchingAccessibleMethod(cls, methodName,
286 args = ArrayUtils.nullToEmpty(args);
287 parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
288 final Method method = getMatchingAccessibleMethod(cls, methodName,
314289 parameterTypes);
315290 if (method == null) {
316291 throw new NoSuchMethodException("No such accessible method: "
320295 }
321296
322297 /**
323 * <p>Invokes a static method whose parameter types match exactly the object
298 * <p>Invokes a {@code static} method whose parameter types match exactly the object
324299 * types.</p>
325300 *
326301 * <p>This uses reflection to invoke the method obtained from a call to
328303 *
329304 * @param cls invoke static method on this class
330305 * @param methodName get method with this name
331 * @param args use these arguments - treat null as empty array
306 * @param args use these arguments - treat {@code null} as empty array
332307 * @return The value returned by the invoked method
333308 *
334309 * @throws NoSuchMethodException if there is no such accessible method
337312 * @throws IllegalAccessException if the requested method is not accessible
338313 * via reflection
339314 */
340 public static Object invokeExactStaticMethod(Class<?> cls, String methodName,
315 public static Object invokeExactStaticMethod(final Class<?> cls, final String methodName,
341316 Object... args) throws NoSuchMethodException,
342317 IllegalAccessException, InvocationTargetException {
343 if (args == null) {
344 args = ArrayUtils.EMPTY_OBJECT_ARRAY;
345 }
346 int arguments = args.length;
347 Class<?>[] parameterTypes = new Class[arguments];
348 for (int i = 0; i < arguments; i++) {
349 parameterTypes[i] = args[i].getClass();
350 }
318 args = ArrayUtils.nullToEmpty(args);
319 final Class<?>[] parameterTypes = ClassUtils.toClass(args);
351320 return invokeExactStaticMethod(cls, methodName, args, parameterTypes);
352321 }
353322
354323 /**
355324 * <p>Returns an accessible method (that is, one that can be invoked via
356 * reflection) with given name and parameters. If no such method
357 * can be found, return <code>null</code>.
358 * This is just a convenient wrapper for
359 * {@link #getAccessibleMethod(Method method)}.</p>
325 * reflection) with given name and parameters. If no such method
326 * can be found, return {@code null}.
327 * This is just a convenience wrapper for
328 * {@link #getAccessibleMethod(Method)}.</p>
360329 *
361330 * @param cls get method from this class
362331 * @param methodName get method with this name
363332 * @param parameterTypes with these parameters types
364333 * @return The accessible method
365334 */
366 public static Method getAccessibleMethod(Class<?> cls, String methodName,
367 Class<?>... parameterTypes) {
335 public static Method getAccessibleMethod(final Class<?> cls, final String methodName,
336 final Class<?>... parameterTypes) {
368337 try {
369338 return getAccessibleMethod(cls.getMethod(methodName,
370339 parameterTypes));
371 } catch (NoSuchMethodException e) {
340 } catch (final NoSuchMethodException e) {
372341 return null;
373342 }
374343 }
375344
376345 /**
377346 * <p>Returns an accessible method (that is, one that can be invoked via
378 * reflection) that implements the specified Method. If no such method
379 * can be found, return <code>null</code>.</p>
347 * reflection) that implements the specified Method. If no such method
348 * can be found, return {@code null}.</p>
380349 *
381350 * @param method The method that we wish to call
382351 * @return The accessible method
386355 return null;
387356 }
388357 // If the declaring class is public, we are done
389 Class<?> cls = method.getDeclaringClass();
358 final Class<?> cls = method.getDeclaringClass();
390359 if (Modifier.isPublic(cls.getModifiers())) {
391360 return method;
392361 }
393 String methodName = method.getName();
394 Class<?>[] parameterTypes = method.getParameterTypes();
362 final String methodName = method.getName();
363 final Class<?>[] parameterTypes = method.getParameterTypes();
395364
396365 // Check the implemented interfaces and subinterfaces
397366 method = getAccessibleMethodFromInterfaceNest(cls, methodName,
408377 /**
409378 * <p>Returns an accessible method (that is, one that can be invoked via
410379 * reflection) by scanning through the superclasses. If no such method
411 * can be found, return <code>null</code>.</p>
380 * can be found, return {@code null}.</p>
412381 *
413382 * @param cls Class to be checked
414383 * @param methodName Method name of the method we wish to call
415384 * @param parameterTypes The parameter type signatures
416 * @return the accessible method or <code>null</code> if not found
417 */
418 private static Method getAccessibleMethodFromSuperclass(Class<?> cls,
419 String methodName, Class<?>... parameterTypes) {
385 * @return the accessible method or {@code null} if not found
386 */
387 private static Method getAccessibleMethodFromSuperclass(final Class<?> cls,
388 final String methodName, final Class<?>... parameterTypes) {
420389 Class<?> parentClass = cls.getSuperclass();
421390 while (parentClass != null) {
422391 if (Modifier.isPublic(parentClass.getModifiers())) {
423392 try {
424393 return parentClass.getMethod(methodName, parameterTypes);
425 } catch (NoSuchMethodException e) {
394 } catch (final NoSuchMethodException e) {
426395 return null;
427396 }
428397 }
434403 /**
435404 * <p>Returns an accessible method (that is, one that can be invoked via
436405 * reflection) that implements the specified method, by scanning through
437 * all implemented interfaces and subinterfaces. If no such method
438 * can be found, return <code>null</code>.</p>
439 *
440 * <p>There isn't any good reason why this method must be private.
406 * all implemented interfaces and subinterfaces. If no such method
407 * can be found, return {@code null}.</p>
408 *
409 * <p>There isn't any good reason why this method must be {@code private}.
441410 * It is because there doesn't seem any reason why other classes should
442411 * call this rather than the higher level methods.</p>
443412 *
444413 * @param cls Parent class for the interfaces to be checked
445414 * @param methodName Method name of the method we wish to call
446415 * @param parameterTypes The parameter type signatures
447 * @return the accessible method or <code>null</code> if not found
416 * @return the accessible method or {@code null} if not found
448417 */
449418 private static Method getAccessibleMethodFromInterfaceNest(Class<?> cls,
450 String methodName, Class<?>... parameterTypes) {
451 Method method = null;
452
419 final String methodName, final Class<?>... parameterTypes) {
453420 // Search up the superclass chain
454421 for (; cls != null; cls = cls.getSuperclass()) {
455422
456423 // Check the implemented interfaces of the parent class
457 Class<?>[] interfaces = cls.getInterfaces();
424 final Class<?>[] interfaces = cls.getInterfaces();
458425 for (int i = 0; i < interfaces.length; i++) {
459426 // Is this interface public?
460427 if (!Modifier.isPublic(interfaces[i].getModifiers())) {
462429 }
463430 // Does the method exist on this interface?
464431 try {
465 method = interfaces[i].getDeclaredMethod(methodName,
432 return interfaces[i].getDeclaredMethod(methodName,
466433 parameterTypes);
467 } catch (NoSuchMethodException e) { // NOPMD
434 } catch (final NoSuchMethodException e) { // NOPMD
468435 /*
469436 * Swallow, if no method is found after the loop then this
470437 * method returns null.
471438 */
472439 }
473 if (method != null) {
474 break;
475 }
476440 // Recursively check our parent interfaces
477 method = getAccessibleMethodFromInterfaceNest(interfaces[i],
441 Method method = getAccessibleMethodFromInterfaceNest(interfaces[i],
478442 methodName, parameterTypes);
479443 if (method != null) {
480 break;
444 return method;
481445 }
482446 }
483447 }
484 return method;
448 return null;
485449 }
486450
487451 /**
496460 * #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
497461 *
498462 * <p>This method can match primitive parameter by passing in wrapper classes.
499 * For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
463 * For example, a {@code Boolean} will match a primitive {@code boolean}
500464 * parameter.
501465 *
502466 * @param cls find method in this class
504468 * @param parameterTypes find method with most compatible parameters
505469 * @return The accessible method
506470 */
507 public static Method getMatchingAccessibleMethod(Class<?> cls,
508 String methodName, Class<?>... parameterTypes) {
471 public static Method getMatchingAccessibleMethod(final Class<?> cls,
472 final String methodName, final Class<?>... parameterTypes) {
509473 try {
510 Method method = cls.getMethod(methodName, parameterTypes);
474 final Method method = cls.getMethod(methodName, parameterTypes);
511475 MemberUtils.setAccessibleWorkaround(method);
512476 return method;
513 } catch (NoSuchMethodException e) { // NOPMD - Swallow the exception
477 } catch (final NoSuchMethodException e) { // NOPMD - Swallow the exception
514478 }
515479 // search through all methods
516480 Method bestMatch = null;
517 Method[] methods = cls.getMethods();
518 for (Method method : methods) {
481 final Method[] methods = cls.getMethods();
482 for (final Method method : methods) {
519483 // compare name and parameters
520484 if (method.getName().equals(methodName) && ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) {
521485 // get accessible version of method
522 Method accessibleMethod = getAccessibleMethod(method);
486 final Method accessibleMethod = getAccessibleMethod(method);
523487 if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareParameterTypes(
524488 accessibleMethod.getParameterTypes(),
525489 bestMatch.getParameterTypes(),
533497 }
534498 return bestMatch;
535499 }
500
501 /**
502 * Get the hierarchy of overridden methods down to {@code result} respecting generics.
503 * @param method lowest to consider
504 * @param interfacesBehavior whether to search interfaces, {@code null} {@code implies} false
505 * @return Set<Method> in ascending order from sub- to superclass
506 * @throws NullPointerException if the specified method is {@code null}
507 * @since 3.2
508 */
509 public static Set<Method> getOverrideHierarchy(final Method method, Interfaces interfacesBehavior) {
510 Validate.notNull(method);
511 final Set<Method> result = new LinkedHashSet<Method>();
512 result.add(method);
513
514 final Class<?>[] parameterTypes = method.getParameterTypes();
515
516 final Class<?> declaringClass = method.getDeclaringClass();
517
518 final Iterator<Class<?>> hierarchy = ClassUtils.hierarchy(declaringClass, interfacesBehavior).iterator();
519 //skip the declaring class :P
520 hierarchy.next();
521 hierarchyTraversal: while (hierarchy.hasNext()) {
522 final Class<?> c = hierarchy.next();
523 final Method m = getMatchingAccessibleMethod(c, method.getName(), parameterTypes);
524 if (m == null) {
525 continue;
526 }
527 if (Arrays.equals(m.getParameterTypes(), parameterTypes)) {
528 // matches without generics
529 result.add(m);
530 continue;
531 }
532 // necessary to get arguments every time in the case that we are including interfaces
533 final Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(declaringClass, m.getDeclaringClass());
534 for (int i = 0; i < parameterTypes.length; i++) {
535 final Type childType = TypeUtils.unrollVariables(typeArguments, method.getGenericParameterTypes()[i]);
536 final Type parentType = TypeUtils.unrollVariables(typeArguments, m.getGenericParameterTypes()[i]);
537 if (!TypeUtils.equals(childType, parentType)) {
538 continue hierarchyTraversal;
539 }
540 }
541 result.add(m);
542 }
543 return result;
544 }
545
536546 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect;
17
18 import java.lang.reflect.Type;
19 import java.lang.reflect.TypeVariable;
20
21 import org.apache.commons.lang3.Validate;
22
23 /**
24 * <p>Type literal comparable to {@code javax.enterprise.util.TypeLiteral},
25 * made generally available outside the JEE context. Allows the passing around of
26 * a "token" that represents a type in a typesafe manner, as opposed to
27 * passing the (non-parameterized) {@link Type} object itself. Consider:</p>
28 * <p>
29 * You might see such a typesafe API as:
30 * <pre>
31 * class Typesafe {
32 * &lt;T&gt; T obtain(Class&lt;T&gt; type, ...);
33 * }
34 * </pre>
35 * Consumed in the manner of:
36 * <pre>
37 * Foo foo = typesafe.obtain(Foo.class, ...);
38 * </pre>
39 * Yet, you run into problems when you want to do this with a parameterized type:
40 * <pre>
41 * List&lt;String&gt; listOfString = typesafe.obtain(List.class, ...); // could only give us a raw List
42 * </pre>
43 * {@code java.lang.reflect.Type} might provide some value:
44 * <pre>
45 * Type listOfStringType = ...; // firstly, how to obtain this? Doable, but not straightforward.
46 * List&lt;String&gt; listOfString = (List&lt;String&gt;) typesafe.obtain(listOfStringType, ...); // nongeneric Type would necessitate a cast
47 * </pre>
48 * The "type literal" concept was introduced to provide an alternative, i.e.:
49 * <pre>
50 * class Typesafe {
51 * &lt;T&gt; T obtain(TypeLiteral&lt;T&gt; type, ...);
52 * }
53 * </pre>
54 * Consuming code looks like:
55 * <pre>
56 * List&lt;String&gt; listOfString = typesafe.obtain(new TypeLiteral&lt;List&lt;String&gt;&gt;() {}, ...);
57 * </pre>
58 * This has the effect of "jumping up" a level to tie a {@code java.lang.reflect.Type}
59 * to a type variable while simultaneously making it short work to obtain a
60 * {@code Type} instance for any given type, inline.
61 * </p>
62 * <p>Additionally {@link TypeLiteral} implements the {@link Typed} interface which
63 * is a generalization of this concept, and which may be implemented in custom classes.
64 * It is suggested that APIs be defined in terms of the interface, in the following manner:
65 * <pre>
66 * &lt;T&gt; T obtain(Typed&lt;T&gt; typed, ...);
67 * </pre>
68 * </p>
69 *
70 * @version $Id: TypeLiteral.java 1552665 2013-12-20 13:43:53Z britter $
71 * @since 3.2
72 */
73 public abstract class TypeLiteral<T> implements Typed<T> {
74
75 @SuppressWarnings("rawtypes")
76 private static final TypeVariable<Class<TypeLiteral>> T = TypeLiteral.class.getTypeParameters()[0];
77
78 /**
79 * Represented type.
80 */
81 public final Type value;
82
83 private final String toString;
84
85 /**
86 * The default constructor.
87 */
88 protected TypeLiteral() {
89 this.value =
90 Validate.notNull(TypeUtils.getTypeArguments(getClass(), TypeLiteral.class).get(T),
91 "%s does not assign type parameter %s", getClass(), TypeUtils.toLongString(T));
92
93 this.toString = String.format("%s<%s>", TypeLiteral.class.getSimpleName(), TypeUtils.toString(value));
94 }
95
96 @Override
97 public final boolean equals(Object obj) {
98 if (obj == this) {
99 return true;
100 }
101 if (obj instanceof TypeLiteral == false) {
102 return false;
103 }
104 final TypeLiteral<?> other = (TypeLiteral<?>) obj;
105 return TypeUtils.equals(value, other.value);
106 }
107
108 @Override
109 public int hashCode() {
110 return 37 << 4 | value.hashCode();
111 }
112
113 @Override
114 public String toString() {
115 return toString;
116 }
117
118 @Override
119 public Type getType() {
120 return value;
121 }
122 }
1717
1818 import java.lang.reflect.Array;
1919 import java.lang.reflect.GenericArrayType;
20 import java.lang.reflect.GenericDeclaration;
2021 import java.lang.reflect.ParameterizedType;
2122 import java.lang.reflect.Type;
2223 import java.lang.reflect.TypeVariable;
2324 import java.lang.reflect.WildcardType;
2425 import java.util.Arrays;
26 import java.util.Collections;
2527 import java.util.HashMap;
2628 import java.util.HashSet;
2729 import java.util.List;
2830 import java.util.Map;
2931 import java.util.Set;
3032
33 import org.apache.commons.lang3.ArrayUtils;
3134 import org.apache.commons.lang3.ClassUtils;
35 import org.apache.commons.lang3.ObjectUtils;
36 import org.apache.commons.lang3.Validate;
37 import org.apache.commons.lang3.builder.Builder;
3238
3339 /**
3440 * <p> Utility methods focusing on type inspection, particularly with regard to
3541 * generics. </p>
3642 *
3743 * @since 3.0
38 * @version $Id: TypeUtils.java 1144929 2011-07-10 18:26:16Z ggregory $
44 * @version $Id: TypeUtils.java 1535763 2013-10-25 15:25:22Z mbenson $
3945 */
4046 public class TypeUtils {
4147
4248 /**
43 * <p> TypeUtils instances should NOT be constructed in standard
49 * {@link WildcardType} builder.
50 * @since 3.2
51 */
52 public static class WildcardTypeBuilder implements Builder<WildcardType> {
53 /**
54 * Constructor
55 */
56 private WildcardTypeBuilder() {
57 }
58
59 private Type[] upperBounds;
60 private Type[] lowerBounds;
61
62 /**
63 * Specify upper bounds of the wildcard type to build.
64 * @param bounds to set
65 * @return {@code this}
66 */
67 public WildcardTypeBuilder withUpperBounds(Type... bounds) {
68 this.upperBounds = bounds;
69 return this;
70 }
71
72 /**
73 * Specify lower bounds of the wildcard type to build.
74 * @param bounds to set
75 * @return {@code this}
76 */
77 public WildcardTypeBuilder withLowerBounds(Type... bounds) {
78 this.lowerBounds = bounds;
79 return this;
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 @Override
86 public WildcardType build() {
87 return new WildcardTypeImpl(upperBounds, lowerBounds);
88 }
89 }
90
91 /**
92 * GenericArrayType implementation class.
93 * @since 3.2
94 */
95 private static final class GenericArrayTypeImpl implements GenericArrayType {
96 private final Type componentType;
97
98 /**
99 * Constructor
100 * @param componentType of this array type
101 */
102 private GenericArrayTypeImpl(Type componentType) {
103 this.componentType = componentType;
104 }
105
106 /**
107 * {@inheritDoc}
108 */
109 @Override
110 public Type getGenericComponentType() {
111 return componentType;
112 }
113
114 /**
115 * {@inheritDoc}
116 */
117 @Override
118 public String toString() {
119 return TypeUtils.toString(this);
120 }
121
122 /**
123 * {@inheritDoc}
124 */
125 @Override
126 public boolean equals(Object obj) {
127 return obj == this || obj instanceof GenericArrayType && TypeUtils.equals(this, (GenericArrayType) obj);
128 }
129
130 /**
131 * {@inheritDoc}
132 */
133 @Override
134 public int hashCode() {
135 int result = 67 << 4;
136 result |= componentType.hashCode();
137 return result;
138 }
139 }
140
141 /**
142 * ParameterizedType implementation class.
143 * @since 3.2
144 */
145 private static final class ParameterizedTypeImpl implements ParameterizedType {
146 private final Class<?> raw;
147 private final Type useOwner;
148 private final Type[] typeArguments;
149
150 /**
151 * Constructor
152 * @param raw type
153 * @param useOwner owner type to use, if any
154 * @param typeArguments formal type arguments
155 */
156 private ParameterizedTypeImpl(Class<?> raw, Type useOwner, Type[] typeArguments) {
157 this.raw = raw;
158 this.useOwner = useOwner;
159 this.typeArguments = typeArguments;
160 }
161
162 /**
163 * {@inheritDoc}
164 */
165 @Override
166 public Type getRawType() {
167 return raw;
168 }
169
170 /**
171 * {@inheritDoc}
172 */
173 @Override
174 public Type getOwnerType() {
175 return useOwner;
176 }
177
178 /**
179 * {@inheritDoc}
180 */
181 @Override
182 public Type[] getActualTypeArguments() {
183 return typeArguments.clone();
184 }
185
186 /**
187 * {@inheritDoc}
188 */
189 @Override
190 public String toString() {
191 return TypeUtils.toString(this);
192 }
193
194 /**
195 * {@inheritDoc}
196 */
197 @Override
198 public boolean equals(Object obj) {
199 return obj == this || obj instanceof ParameterizedType && TypeUtils.equals(this, ((ParameterizedType) obj));
200 }
201
202 /**
203 * {@inheritDoc}
204 */
205 @Override
206 public int hashCode() {
207 int result = 71 << 4;
208 result |= raw.hashCode();
209 result <<= 4;
210 result |= ObjectUtils.hashCode(useOwner);
211 result <<= 8;
212 result |= Arrays.hashCode(typeArguments);
213 return result;
214 }
215 }
216
217 /**
218 * WildcardType implementation class.
219 * @since 3.2
220 */
221 private static final class WildcardTypeImpl implements WildcardType {
222 private static final Type[] EMPTY_BOUNDS = new Type[0];
223
224 private final Type[] upperBounds;
225 private final Type[] lowerBounds;
226
227 /**
228 * Constructor
229 * @param upperBounds of this type
230 * @param lowerBounds of this type
231 */
232 private WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
233 this.upperBounds = ObjectUtils.defaultIfNull(upperBounds, EMPTY_BOUNDS);
234 this.lowerBounds = ObjectUtils.defaultIfNull(lowerBounds, EMPTY_BOUNDS);
235 }
236
237 /**
238 * {@inheritDoc}
239 */
240 @Override
241 public Type[] getUpperBounds() {
242 return upperBounds.clone();
243 }
244
245 /**
246 * {@inheritDoc}
247 */
248 @Override
249 public Type[] getLowerBounds() {
250 return lowerBounds.clone();
251 }
252
253 /**
254 * {@inheritDoc}
255 */
256 @Override
257 public String toString() {
258 return TypeUtils.toString(this);
259 }
260
261 /**
262 * {@inheritDoc}
263 */
264 @Override
265 public boolean equals(Object obj) {
266 return obj == this || obj instanceof WildcardType && TypeUtils.equals(this, (WildcardType) obj);
267 }
268
269 /**
270 * {@inheritDoc}
271 */
272 @Override
273 public int hashCode() {
274 int result = 73 << 8;
275 result |= Arrays.hashCode(upperBounds);
276 result <<= 8;
277 result |= Arrays.hashCode(lowerBounds);
278 return result;
279 }
280 }
281
282 /**
283 * A wildcard instance matching {@code ?}.
284 * @since 3.2
285 */
286 public static final WildcardType WILDCARD_ALL = wildcardType().withUpperBounds(Object.class).build();
287
288 /**
289 * <p>{@code TypeUtils} instances should NOT be constructed in standard
44290 * programming. Instead, the class should be used as
45 * <code>TypeUtils.isAssignable(cls, toClass)</code>. </p> <p> This
291 * {@code TypeUtils.isAssignable(cls, toClass)}.</p> <p>This
46292 * constructor is public to permit tools that require a JavaBean instance to
47 * operate. </p>
293 * operate.</p>
48294 */
49295 public TypeUtils() {
50296 super();
51297 }
52298
53299 /**
54 * <p> Checks if the subject type may be implicitly cast to the target type
300 * <p>Checks if the subject type may be implicitly cast to the target type
55301 * following the Java generics rules. If both types are {@link Class}
56302 * objects, the method returns the result of
57 * {@link ClassUtils#isAssignable(Class, Class)}. </p>
303 * {@link ClassUtils#isAssignable(Class, Class)}.</p>
58304 *
59305 * @param type the subject type to be assigned to the target type
60306 * @param toType the target type
61 * @return <code>true</code> if <code>type</code> is assignable to <code>toType</code>.
62 */
63 public static boolean isAssignable(Type type, Type toType) {
307 * @return {@code true} if {@code type} is assignable to {@code toType}.
308 */
309 public static boolean isAssignable(final Type type, final Type toType) {
64310 return isAssignable(type, toType, null);
65311 }
66312
67313 /**
68 * <p> Checks if the subject type may be implicitly cast to the target type
69 * following the Java generics rules. </p>
314 * <p>Checks if the subject type may be implicitly cast to the target type
315 * following the Java generics rules.</p>
70316 *
71317 * @param type the subject type to be assigned to the target type
72318 * @param toType the target type
73319 * @param typeVarAssigns optional map of type variable assignments
74 * @return <code>true</code> if <code>type</code> is assignable to <code>toType</code>.
75 */
76 private static boolean isAssignable(Type type, Type toType,
77 Map<TypeVariable<?>, Type> typeVarAssigns) {
320 * @return {@code true} if {@code type} is assignable to {@code toType}.
321 */
322 private static boolean isAssignable(final Type type, final Type toType,
323 final Map<TypeVariable<?>, Type> typeVarAssigns) {
78324 if (toType == null || toType instanceof Class<?>) {
79325 return isAssignable(type, (Class<?>) toType);
80326 }
91337 return isAssignable(type, (WildcardType) toType, typeVarAssigns);
92338 }
93339
94 // *
95340 if (toType instanceof TypeVariable<?>) {
96341 return isAssignable(type, (TypeVariable<?>) toType, typeVarAssigns);
97342 }
98 // */
99343
100344 throw new IllegalStateException("found an unhandled type: " + toType);
101345 }
102346
103347 /**
104 * <p> Checks if the subject type may be implicitly cast to the target class
105 * following the Java generics rules. </p>
348 * <p>Checks if the subject type may be implicitly cast to the target class
349 * following the Java generics rules.</p>
106350 *
107351 * @param type the subject type to be assigned to the target type
108352 * @param toClass the target class
109 * @return true if <code>type</code> is assignable to <code>toClass</code>.
110 */
111 private static boolean isAssignable(Type type, Class<?> toClass) {
353 * @return {@code true} if {@code type} is assignable to {@code toClass}.
354 */
355 private static boolean isAssignable(final Type type, final Class<?> toClass) {
112356 if (type == null) {
113357 // consistency with ClassUtils.isAssignable() behavior
114358 return toClass == null || !toClass.isPrimitive();
139383 if (type instanceof TypeVariable<?>) {
140384 // if any of the bounds are assignable to the class, then the
141385 // type is assignable to the class.
142 for (Type bound : ((TypeVariable<?>) type).getBounds()) {
386 for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
143387 if (isAssignable(bound, toClass)) {
144388 return true;
145389 }
167411 }
168412
169413 /**
170 * <p> Checks if the subject type may be implicitly cast to the target
171 * parameterized type following the Java generics rules. </p>
414 * <p>Checks if the subject type may be implicitly cast to the target
415 * parameterized type following the Java generics rules.</p>
172416 *
173417 * @param type the subject type to be assigned to the target type
174418 * @param toParameterizedType the target parameterized type
175419 * @param typeVarAssigns a map with type variables
176 * @return true if <code>type</code> is assignable to <code>toType</code>.
177 */
178 private static boolean isAssignable(Type type, ParameterizedType toParameterizedType,
179 Map<TypeVariable<?>, Type> typeVarAssigns) {
420 * @return {@code true} if {@code type} is assignable to {@code toType}.
421 */
422 private static boolean isAssignable(final Type type, final ParameterizedType toParameterizedType,
423 final Map<TypeVariable<?>, Type> typeVarAssigns) {
180424 if (type == null) {
181425 return true;
182426 }
193437 }
194438
195439 // get the target type's raw type
196 Class<?> toClass = getRawType(toParameterizedType);
440 final Class<?> toClass = getRawType(toParameterizedType);
197441 // get the subject type's type arguments including owner type arguments
198442 // and supertype arguments up to and including the target class.
199 Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null);
443 final Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null);
200444
201445 // null means the two types are not compatible
202446 if (fromTypeVarAssigns == null) {
211455 }
212456
213457 // get the target type's type arguments including owner type arguments
214 Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(toParameterizedType,
458 final Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(toParameterizedType,
215459 toClass, typeVarAssigns);
216460
217461 // now to check each type argument
218 for (Map.Entry<TypeVariable<?>, Type> entry : toTypeVarAssigns.entrySet()) {
219 Type toTypeArg = entry.getValue();
220 Type fromTypeArg = fromTypeVarAssigns.get(entry.getKey());
462 for (final TypeVariable<?> var : toTypeVarAssigns.keySet()) {
463 final Type toTypeArg = unrollVariableAssignments(var, toTypeVarAssigns);
464 final Type fromTypeArg = unrollVariableAssignments(var, fromTypeVarAssigns);
221465
222466 // parameters must either be absent from the subject type, within
223467 // the bounds of the wildcard type, or be an exact match to the
229473 return false;
230474 }
231475 }
232
233476 return true;
234477 }
235478
236479 /**
237 * <p> Checks if the subject type may be implicitly cast to the target
238 * generic array type following the Java generics rules. </p>
480 * Look up {@code var} in {@code typeVarAssigns} <em>transitively</em>,
481 * i.e. keep looking until the value found is <em>not</em> a type variable.
482 * @param var the type variable to look up
483 * @param typeVarAssigns the map used for the look up
484 * @return Type or {@code null} if some variable was not in the map
485 * @since 3.2
486 */
487 private static Type unrollVariableAssignments(TypeVariable<?> var, final Map<TypeVariable<?>, Type> typeVarAssigns) {
488 Type result;
489 do {
490 result = typeVarAssigns.get(var);
491 if (result instanceof TypeVariable<?> && !result.equals(var)) {
492 var = (TypeVariable<?>) result;
493 continue;
494 }
495 break;
496 } while (true);
497 return result;
498 }
499
500 /**
501 * <p>Checks if the subject type may be implicitly cast to the target
502 * generic array type following the Java generics rules.</p>
239503 *
240504 * @param type the subject type to be assigned to the target type
241505 * @param toGenericArrayType the target generic array type
242506 * @param typeVarAssigns a map with type variables
243 * @return true if <code>type</code> is assignable to
244 * <code>toGenericArrayType</code>.
245 */
246 private static boolean isAssignable(Type type, GenericArrayType toGenericArrayType,
247 Map<TypeVariable<?>, Type> typeVarAssigns) {
507 * @return {@code true} if {@code type} is assignable to
508 * {@code toGenericArrayType}.
509 */
510 private static boolean isAssignable(final Type type, final GenericArrayType toGenericArrayType,
511 final Map<TypeVariable<?>, Type> typeVarAssigns) {
248512 if (type == null) {
249513 return true;
250514 }
260524 return true;
261525 }
262526
263 Type toComponentType = toGenericArrayType.getGenericComponentType();
527 final Type toComponentType = toGenericArrayType.getGenericComponentType();
264528
265529 if (type instanceof Class<?>) {
266 Class<?> cls = (Class<?>) type;
530 final Class<?> cls = (Class<?>) type;
267531
268532 // compare the component types
269533 return cls.isArray()
278542
279543 if (type instanceof WildcardType) {
280544 // so long as one of the upper bounds is assignable, it's good
281 for (Type bound : getImplicitUpperBounds((WildcardType) type)) {
545 for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
282546 if (isAssignable(bound, toGenericArrayType)) {
283547 return true;
284548 }
290554 if (type instanceof TypeVariable<?>) {
291555 // probably should remove the following logic and just return false.
292556 // type variables cannot specify arrays as bounds.
293 for (Type bound : getImplicitBounds((TypeVariable<?>) type)) {
557 for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
294558 if (isAssignable(bound, toGenericArrayType)) {
295559 return true;
296560 }
310574 }
311575
312576 /**
313 * <p> Checks if the subject type may be implicitly cast to the target
314 * wildcard type following the Java generics rules. </p>
577 * <p>Checks if the subject type may be implicitly cast to the target
578 * wildcard type following the Java generics rules.</p>
315579 *
316580 * @param type the subject type to be assigned to the target type
317581 * @param toWildcardType the target wildcard type
318582 * @param typeVarAssigns a map with type variables
319 * @return true if <code>type</code> is assignable to
320 * <code>toWildcardType</code>.
321 */
322 private static boolean isAssignable(Type type, WildcardType toWildcardType,
323 Map<TypeVariable<?>, Type> typeVarAssigns) {
583 * @return {@code true} if {@code type} is assignable to
584 * {@code toWildcardType}.
585 */
586 private static boolean isAssignable(final Type type, final WildcardType toWildcardType,
587 final Map<TypeVariable<?>, Type> typeVarAssigns) {
324588 if (type == null) {
325589 return true;
326590 }
336600 return true;
337601 }
338602
339 Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType);
340 Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType);
603 final Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType);
604 final Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType);
341605
342606 if (type instanceof WildcardType) {
343 WildcardType wildcardType = (WildcardType) type;
344 Type[] upperBounds = getImplicitUpperBounds(wildcardType);
345 Type[] lowerBounds = getImplicitLowerBounds(wildcardType);
607 final WildcardType wildcardType = (WildcardType) type;
608 final Type[] upperBounds = getImplicitUpperBounds(wildcardType);
609 final Type[] lowerBounds = getImplicitLowerBounds(wildcardType);
346610
347611 for (Type toBound : toUpperBounds) {
348612 // if there are assignments for unresolved type variables,
352616 // each upper bound of the subject type has to be assignable to
353617 // each
354618 // upper bound of the target type
355 for (Type bound : upperBounds) {
619 for (final Type bound : upperBounds) {
356620 if (!isAssignable(bound, toBound, typeVarAssigns)) {
357621 return false;
358622 }
367631 // each lower bound of the target type has to be assignable to
368632 // each
369633 // lower bound of the subject type
370 for (Type bound : lowerBounds) {
634 for (final Type bound : lowerBounds) {
371635 if (!isAssignable(toBound, bound, typeVarAssigns)) {
372636 return false;
373637 }
374638 }
375639 }
376
377640 return true;
378641 }
379642
380 for (Type toBound : toUpperBounds) {
643 for (final Type toBound : toUpperBounds) {
381644 // if there are assignments for unresolved type variables,
382645 // now's the time to substitute them.
383646 if (!isAssignable(type, substituteTypeVariables(toBound, typeVarAssigns),
386649 }
387650 }
388651
389 for (Type toBound : toLowerBounds) {
652 for (final Type toBound : toLowerBounds) {
390653 // if there are assignments for unresolved type variables,
391654 // now's the time to substitute them.
392655 if (!isAssignable(substituteTypeVariables(toBound, typeVarAssigns), type,
394657 return false;
395658 }
396659 }
397
398660 return true;
399661 }
400662
401663 /**
402 * <p> Checks if the subject type may be implicitly cast to the target type
403 * variable following the Java generics rules. </p>
664 * <p>Checks if the subject type may be implicitly cast to the target type
665 * variable following the Java generics rules.</p>
404666 *
405667 * @param type the subject type to be assigned to the target type
406668 * @param toTypeVariable the target type variable
407669 * @param typeVarAssigns a map with type variables
408 * @return true if <code>type</code> is assignable to
409 * <code>toTypeVariable</code>.
410 */
411 private static boolean isAssignable(Type type, TypeVariable<?> toTypeVariable,
412 Map<TypeVariable<?>, Type> typeVarAssigns) {
670 * @return {@code true} if {@code type} is assignable to
671 * {@code toTypeVariable}.
672 */
673 private static boolean isAssignable(final Type type, final TypeVariable<?> toTypeVariable,
674 final Map<TypeVariable<?>, Type> typeVarAssigns) {
413675 if (type == null) {
414676 return true;
415677 }
429691 // a type variable is assignable to another type variable, if
430692 // and only if the former is the latter, extends the latter, or
431693 // is otherwise a descendant of the latter.
432 Type[] bounds = getImplicitBounds((TypeVariable<?>) type);
433
434 for (Type bound : bounds) {
694 final Type[] bounds = getImplicitBounds((TypeVariable<?>) type);
695
696 for (final Type bound : bounds) {
435697 if (isAssignable(bound, toTypeVariable, typeVarAssigns)) {
436698 return true;
437699 }
447709 }
448710
449711 /**
450 * <p> </p>
712 * <p>Find the mapping for {@code type} in {@code typeVarAssigns}.</p>
451713 *
452714 * @param type the type to be replaced
453715 * @param typeVarAssigns the map with type variables
454716 * @return the replaced type
455717 * @throws IllegalArgumentException if the type cannot be substituted
456718 */
457 private static Type substituteTypeVariables(Type type, Map<TypeVariable<?>, Type> typeVarAssigns) {
719 private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) {
458720 if (type instanceof TypeVariable<?> && typeVarAssigns != null) {
459 Type replacementType = typeVarAssigns.get(type);
721 final Type replacementType = typeVarAssigns.get(type);
460722
461723 if (replacementType == null) {
462724 throw new IllegalArgumentException("missing assignment type for type variable "
463725 + type);
464726 }
465
466727 return replacementType;
467728 }
468
469729 return type;
470730 }
471731
472732 /**
473 * <p> Retrieves all the type arguments for this parameterized type
474 * including owner hierarchy arguments such as <code>
475 * Outer<K,V>.Inner<T>.DeepInner<E></code> . The arguments are returned in a
733 * <p>Retrieves all the type arguments for this parameterized type
734 * including owner hierarchy arguments such as
735 * {@code Outer<K,V>.Inner<T>.DeepInner<E>} .
736 * The arguments are returned in a
476737 * {@link Map} specifying the argument type for each {@link TypeVariable}.
477738 * </p>
478739 *
479740 * @param type specifies the subject parameterized type from which to
480 * harvest the parameters.
481 * @return a map of the type arguments to their respective type variables.
482 */
483 public static Map<TypeVariable<?>, Type> getTypeArguments(ParameterizedType type) {
741 * harvest the parameters.
742 * @return a {@code Map} of the type arguments to their respective type
743 * variables.
744 */
745 public static Map<TypeVariable<?>, Type> getTypeArguments(final ParameterizedType type) {
484746 return getTypeArguments(type, getRawType(type), null);
485747 }
486748
487749 /**
488 * <p> Gets the type arguments of a class/interface based on a subtype. For
750 * <p>Gets the type arguments of a class/interface based on a subtype. For
489751 * instance, this method will determine that both of the parameters for the
490752 * interface {@link Map} are {@link Object} for the subtype
491753 * {@link java.util.Properties Properties} even though the subtype does not
492 * directly implement the <code>Map</code> interface. <p> </p> This method
493 * returns <code>null</code> if <code>type</code> is not assignable to
494 * <code>toClass</code>. It returns an empty map if none of the classes or
495 * interfaces in its inheritance hierarchy specify any type arguments. </p>
496 * <p> A side-effect of this method is that it also retrieves the type
754 * directly implement the {@code Map} interface.<p> </p>This method
755 * returns {@code null} if {@code type} is not assignable to
756 * {@code toClass}. It returns an empty map if none of the classes or
757 * interfaces in its inheritance hierarchy specify any type arguments.</p>
758 * <p>A side effect of this method is that it also retrieves the type
497759 * arguments for the classes and interfaces that are part of the hierarchy
498 * between <code>type</code> and <code>toClass</code>. So with the above
760 * between {@code type} and {@code toClass}. So with the above
499761 * example, this method will also determine that the type arguments for
500 * {@link java.util.Hashtable Hashtable} are also both <code>Object</code>.
501 * In cases where the interface specified by <code>toClass</code> is
502 * (indirectly) implemented more than once (e.g. where <code>toClass</code>
762 * {@link java.util.Hashtable Hashtable} are also both {@code Object}.
763 * In cases where the interface specified by {@code toClass} is
764 * (indirectly) implemented more than once (e.g. where {@code toClass}
503765 * specifies the interface {@link java.lang.Iterable Iterable} and
504 * <code>type</code> specifies a parameterized type that implements both
766 * {@code type} specifies a parameterized type that implements both
505767 * {@link java.util.Set Set} and {@link java.util.Collection Collection}),
506768 * this method will look at the inheritance hierarchy of only one of the
507769 * implementations/subclasses; the first interface encountered that isn't a
508 * subinterface to one of the others in the <code>type</code> to
509 * <code>toClass</code> hierarchy. </p>
770 * subinterface to one of the others in the {@code type} to
771 * {@code toClass} hierarchy.</p>
510772 *
511773 * @param type the type from which to determine the type parameters of
512 * <code>toClass</code>
774 * {@code toClass}
513775 * @param toClass the class whose type parameters are to be determined based
514 * on the subtype <code>type</code>
515 * @return a map of the type assignments for the type variables in each type
516 * in the inheritance hierarchy from <code>type</code> to
517 * <code>toClass</code> inclusive.
518 */
519 public static Map<TypeVariable<?>, Type> getTypeArguments(Type type, Class<?> toClass) {
776 * on the subtype {@code type}
777 * @return a {@code Map} of the type assignments for the type variables in
778 * each type in the inheritance hierarchy from {@code type} to
779 * {@code toClass} inclusive.
780 */
781 public static Map<TypeVariable<?>, Type> getTypeArguments(final Type type, final Class<?> toClass) {
520782 return getTypeArguments(type, toClass, null);
521783 }
522784
523785 /**
524 * <p> Return a map of the type arguments of <code>type</code> in the context of <code>toClass</code>. </p>
786 * <p>Return a map of the type arguments of @{code type} in the context of {@code toClass}.</p>
525787 *
526788 * @param type the type in question
527789 * @param toClass the class
528790 * @param subtypeVarAssigns a map with type variables
529 * @return the map with type arguments
530 */
531 private static Map<TypeVariable<?>, Type> getTypeArguments(Type type, Class<?> toClass,
532 Map<TypeVariable<?>, Type> subtypeVarAssigns) {
791 * @return the {@code Map} with type arguments
792 */
793 private static Map<TypeVariable<?>, Type> getTypeArguments(final Type type, final Class<?> toClass,
794 final Map<TypeVariable<?>, Type> subtypeVarAssigns) {
533795 if (type instanceof Class<?>) {
534796 return getTypeArguments((Class<?>) type, toClass, subtypeVarAssigns);
535797 }
546808 // since wildcard types are not assignable to classes, should this just
547809 // return null?
548810 if (type instanceof WildcardType) {
549 for (Type bound : getImplicitUpperBounds((WildcardType) type)) {
811 for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
550812 // find the first bound that is assignable to the target class
551813 if (isAssignable(bound, toClass)) {
552814 return getTypeArguments(bound, toClass, subtypeVarAssigns);
556818 return null;
557819 }
558820
559 // *
560821 if (type instanceof TypeVariable<?>) {
561 for (Type bound : getImplicitBounds((TypeVariable<?>) type)) {
822 for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
562823 // find the first bound that is assignable to the target class
563824 if (isAssignable(bound, toClass)) {
564825 return getTypeArguments(bound, toClass, subtypeVarAssigns);
567828
568829 return null;
569830 }
570 // */
571
572831 throw new IllegalStateException("found an unhandled type: " + type);
573832 }
574833
575834 /**
576 * <p> Return a map of the type arguments of a parameterized type in the context of <code>toClass</code>. </p>
835 * <p>Return a map of the type arguments of a parameterized type in the context of {@code toClass}.</p>
577836 *
578837 * @param parameterizedType the parameterized type
579838 * @param toClass the class
580839 * @param subtypeVarAssigns a map with type variables
581 * @return the map with type arguments
840 * @return the {@code Map} with type arguments
582841 */
583842 private static Map<TypeVariable<?>, Type> getTypeArguments(
584 ParameterizedType parameterizedType, Class<?> toClass,
585 Map<TypeVariable<?>, Type> subtypeVarAssigns) {
586 Class<?> cls = getRawType(parameterizedType);
843 final ParameterizedType parameterizedType, final Class<?> toClass,
844 final Map<TypeVariable<?>, Type> subtypeVarAssigns) {
845 final Class<?> cls = getRawType(parameterizedType);
587846
588847 // make sure they're assignable
589848 if (!isAssignable(cls, toClass)) {
590849 return null;
591850 }
592851
593 Type ownerType = parameterizedType.getOwnerType();
852 final Type ownerType = parameterizedType.getOwnerType();
594853 Map<TypeVariable<?>, Type> typeVarAssigns;
595854
596855 if (ownerType instanceof ParameterizedType) {
597856 // get the owner type arguments first
598 ParameterizedType parameterizedOwnerType = (ParameterizedType) ownerType;
857 final ParameterizedType parameterizedOwnerType = (ParameterizedType) ownerType;
599858 typeVarAssigns = getTypeArguments(parameterizedOwnerType,
600859 getRawType(parameterizedOwnerType), subtypeVarAssigns);
601860 } else {
605864 }
606865
607866 // get the subject parameterized type's arguments
608 Type[] typeArgs = parameterizedType.getActualTypeArguments();
867 final Type[] typeArgs = parameterizedType.getActualTypeArguments();
609868 // and get the corresponding type variables from the raw class
610 TypeVariable<?>[] typeParams = cls.getTypeParameters();
869 final TypeVariable<?>[] typeParams = cls.getTypeParameters();
611870
612871 // map the arguments to their respective type variables
613872 for (int i = 0; i < typeParams.length; i++) {
614 Type typeArg = typeArgs[i];
873 final Type typeArg = typeArgs[i];
615874 typeVarAssigns.put(typeParams[i], typeVarAssigns.containsKey(typeArg) ? typeVarAssigns
616875 .get(typeArg) : typeArg);
617876 }
626885 }
627886
628887 /**
629 * <p> Return a map of the type arguments of a class in the context of <code>toClass</code>. </p>
888 * <p>Return a map of the type arguments of a class in the context of @{code toClass}.</p>
630889 *
631890 * @param cls the class in question
632891 * @param toClass the context class
633892 * @param subtypeVarAssigns a map with type variables
634 * @return the map with type arguments
635 */
636 private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls, Class<?> toClass,
637 Map<TypeVariable<?>, Type> subtypeVarAssigns) {
893 * @return the {@code Map} with type arguments
894 */
895 private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls, final Class<?> toClass,
896 final Map<TypeVariable<?>, Type> subtypeVarAssigns) {
638897 // make sure they're assignable
639898 if (!isAssignable(cls, toClass)) {
640899 return null;
654913 }
655914
656915 // create a copy of the incoming map, or an empty one if it's null
657 HashMap<TypeVariable<?>, Type> typeVarAssigns = subtypeVarAssigns == null ? new HashMap<TypeVariable<?>, Type>()
916 final HashMap<TypeVariable<?>, Type> typeVarAssigns = subtypeVarAssigns == null ? new HashMap<TypeVariable<?>, Type>()
658917 : new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);
659918
660 // no arguments for the parameters, or target class has been reached
661 if (cls.getTypeParameters().length > 0 || toClass.equals(cls)) {
919 // has target class been reached?
920 if (toClass.equals(cls)) {
662921 return typeVarAssigns;
663922 }
664923
667926 }
668927
669928 /**
670 * <p> Tries to determine the type arguments of a class/interface based on a
929 * <p>Tries to determine the type arguments of a class/interface based on a
671930 * super parameterized type's type arguments. This method is the inverse of
672931 * {@link #getTypeArguments(Type, Class)} which gets a class/interface's
673932 * type arguments based on a subtype. It is far more limited in determining
674933 * the type arguments for the subject class's type variables in that it can
675934 * only determine those parameters that map from the subject {@link Class}
676 * object to the supertype. </p> <p> Example: {@link java.util.TreeSet
935 * object to the supertype.</p> <p>Example: {@link java.util.TreeSet
677936 * TreeSet} sets its parameter as the parameter for
678937 * {@link java.util.NavigableSet NavigableSet}, which in turn sets the
679938 * parameter of {@link java.util.SortedSet}, which in turn sets the
680939 * parameter of {@link Set}, which in turn sets the parameter of
681940 * {@link java.util.Collection}, which in turn sets the parameter of
682 * {@link java.lang.Iterable}. Since <code>TreeSet</code>'s parameter maps
683 * (indirectly) to <code>Iterable</code>'s parameter, it will be able to
684 * determine that based on the super type <code>Iterable<? extends
685 * Map<Integer,? extends Collection<?>>></code>, the parameter of
686 * <code>TreeSet</code> is <code>? extends Map<Integer,? extends
687 * Collection<?>></code>. </p>
688 *
689 * @param cls the class whose type parameters are to be determined
690 * @param superType the super type from which <code>cls</code>'s type
691 * arguments are to be determined
692 * @return a map of the type assignments that could be determined for the
693 * type variables in each type in the inheritance hierarchy from
694 * <code>type</code> to <code>toClass</code> inclusive.
695 */
696 public static Map<TypeVariable<?>, Type> determineTypeArguments(Class<?> cls,
697 ParameterizedType superType) {
698 Class<?> superClass = getRawType(superType);
941 * {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
942 * (indirectly) to {@code Iterable}'s parameter, it will be able to
943 * determine that based on the super type {@code Iterable<? extends
944 * Map<Integer, ? extends Collection<?>>>}, the parameter of
945 * {@code TreeSet} is {@code ? extends Map<Integer, ? extends
946 * Collection<?>>}.</p>
947 *
948 * @param cls the class whose type parameters are to be determined, not {@code null}
949 * @param superType the super type from which {@code cls}'s type
950 * arguments are to be determined, not {@code null}
951 * @return a {@code Map} of the type assignments that could be determined
952 * for the type variables in each type in the inheritance hierarchy from
953 * {@code type} to {@code toClass} inclusive.
954 */
955 public static Map<TypeVariable<?>, Type> determineTypeArguments(final Class<?> cls,
956 final ParameterizedType superType) {
957 Validate.notNull(cls, "cls is null");
958 Validate.notNull(superType, "superType is null");
959
960 final Class<?> superClass = getRawType(superType);
699961
700962 // compatibility check
701963 if (!isAssignable(cls, superClass)) {
707969 }
708970
709971 // get the next class in the inheritance hierarchy
710 Type midType = getClosestParentType(cls, superClass);
972 final Type midType = getClosestParentType(cls, superClass);
711973
712974 // can only be a class or a parameterized type
713975 if (midType instanceof Class<?>) {
714976 return determineTypeArguments((Class<?>) midType, superType);
715977 }
716978
717 ParameterizedType midParameterizedType = (ParameterizedType) midType;
718 Class<?> midClass = getRawType(midParameterizedType);
979 final ParameterizedType midParameterizedType = (ParameterizedType) midType;
980 final Class<?> midClass = getRawType(midParameterizedType);
719981 // get the type variables of the mid class that map to the type
720982 // arguments of the super class
721 Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(midClass, superType);
983 final Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(midClass, superType);
722984 // map the arguments of the mid type to the class type variables
723985 mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns);
724986
733995 * @param parameterizedType the parameterized type
734996 * @param typeVarAssigns the map to be filled
735997 */
736 private static <T> void mapTypeVariablesToArguments(Class<T> cls,
737 ParameterizedType parameterizedType, Map<TypeVariable<?>, Type> typeVarAssigns) {
998 private static <T> void mapTypeVariablesToArguments(final Class<T> cls,
999 final ParameterizedType parameterizedType, final Map<TypeVariable<?>, Type> typeVarAssigns) {
7381000 // capture the type variables from the owner type that have assignments
739 Type ownerType = parameterizedType.getOwnerType();
1001 final Type ownerType = parameterizedType.getOwnerType();
7401002
7411003 if (ownerType instanceof ParameterizedType) {
7421004 // recursion to make sure the owner's owner type gets processed
7471009 // hierarchy of said interface/class) implemented/extended by the class
7481010 // cls. Find out which type variables of cls are type arguments of
7491011 // parameterizedType:
750 Type[] typeArgs = parameterizedType.getActualTypeArguments();
1012 final Type[] typeArgs = parameterizedType.getActualTypeArguments();
7511013
7521014 // of the cls's type variables that are arguments of parameterizedType,
7531015 // find out which ones can be determined from the super type's arguments
754 TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters();
1016 final TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters();
7551017
7561018 // use List view of type parameters of cls so the contains() method can be used:
757 List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls
1019 final List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls
7581020 .getTypeParameters());
7591021
7601022 for (int i = 0; i < typeArgs.length; i++) {
761 TypeVariable<?> typeVar = typeVars[i];
762 Type typeArg = typeArgs[i];
1023 final TypeVariable<?> typeVar = typeVars[i];
1024 final Type typeArg = typeArgs[i];
7631025
7641026 // argument of parameterizedType is a type variable of cls
7651027 if (typeVarList.contains(typeArg)
7731035 }
7741036
7751037 /**
776 * <p> Closest parent type? Closest to what? The closest parent type to the
777 * super class specified by <code>superClass</code>. </p>
1038 * <p>Get the closest parent type to the
1039 * super class specified by {@code superClass}.</p>
7781040 *
7791041 * @param cls the class in question
7801042 * @param superClass the super class
7811043 * @return the closes parent type
7821044 */
783 private static Type getClosestParentType(Class<?> cls, Class<?> superClass) {
1045 private static Type getClosestParentType(final Class<?> cls, final Class<?> superClass) {
7841046 // only look at the interfaces if the super class is also an interface
7851047 if (superClass.isInterface()) {
7861048 // get the generic interfaces of the subject class
787 Type[] interfaceTypes = cls.getGenericInterfaces();
1049 final Type[] interfaceTypes = cls.getGenericInterfaces();
7881050 // will hold the best generic interface match found
7891051 Type genericInterface = null;
7901052
7911053 // find the interface closest to the super class
792 for (Type midType : interfaceTypes) {
1054 for (final Type midType : interfaceTypes) {
7931055 Class<?> midClass = null;
7941056
7951057 if (midType instanceof ParameterizedType) {
8211083 }
8221084
8231085 /**
824 * <p> Checks if the given value can be assigned to the target type
825 * following the Java generics rules. </p>
1086 * <p>Checks if the given value can be assigned to the target type
1087 * following the Java generics rules.</p>
8261088 *
8271089 * @param value the value to be checked
8281090 * @param type the target type
829 * @return true of <code>value</code> is an instance of <code>type</code>.
830 */
831 public static boolean isInstance(Object value, Type type) {
1091 * @return {@code true} if {@code value} is an instance of {@code type}.
1092 */
1093 public static boolean isInstance(final Object value, final Type type) {
8321094 if (type == null) {
8331095 return false;
8341096 }
8381100 }
8391101
8401102 /**
841 * <p> This method strips out the redundant upper bound types in type
1103 * <p>This method strips out the redundant upper bound types in type
8421104 * variable types and wildcard types (or it would with wildcard types if
843 * multiple upper bounds were allowed). </p> <p> Example: with the variable
1105 * multiple upper bounds were allowed).</p> <p>Example, with the variable
8441106 * type declaration:
8451107 *
846 * <pre> &lt;K extends java.util.Collection&lt;String&gt; &amp;
847 * java.util.List&lt;String&gt;&gt; </pre>
848 *
849 * since <code>List</code> is a subinterface of <code>Collection</code>,
1108 * <pre>&lt;K extends java.util.Collection&lt;String&gt; &amp;
1109 * java.util.List&lt;String&gt;&gt;</pre>
1110 *
1111 * since {@code List} is a subinterface of {@code Collection},
8501112 * this method will return the bounds as if the declaration had been:
8511113 *
852 * <pre> &lt;K extends java.util.List&lt;String&gt;&gt; </pre>
1114 * <pre>&lt;K extends java.util.List&lt;String&gt;&gt;</pre>
8531115 *
8541116 * </p>
8551117 *
8561118 * @param bounds an array of types representing the upper bounds of either
857 * <code>WildcardType</code> or <code>TypeVariable</code>.
858 * @return an array containing the values from <code>bounds</code> minus the
1119 * {@link WildcardType} or {@link TypeVariable}, not {@code null}.
1120 * @return an array containing the values from {@code bounds} minus the
8591121 * redundant types.
8601122 */
861 public static Type[] normalizeUpperBounds(Type[] bounds) {
1123 public static Type[] normalizeUpperBounds(final Type[] bounds) {
1124 Validate.notNull(bounds, "null value specified for bounds array");
8621125 // don't bother if there's only one (or none) type
8631126 if (bounds.length < 2) {
8641127 return bounds;
8651128 }
8661129
867 Set<Type> types = new HashSet<Type>(bounds.length);
868
869 for (Type type1 : bounds) {
1130 final Set<Type> types = new HashSet<Type>(bounds.length);
1131
1132 for (final Type type1 : bounds) {
8701133 boolean subtypeFound = false;
8711134
872 for (Type type2 : bounds) {
1135 for (final Type type2 : bounds) {
8731136 if (type1 != type2 && isAssignable(type2, type1, null)) {
8741137 subtypeFound = true;
8751138 break;
8851148 }
8861149
8871150 /**
888 * <p> Returns an array containing the sole type of {@link Object} if
1151 * <p>Returns an array containing the sole type of {@link Object} if
8891152 * {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it
890 * returns the result of <code>TypeVariable.getBounds()</code> passed into
891 * {@link #normalizeUpperBounds}. </p>
892 *
893 * @param typeVariable the subject type variable
1153 * returns the result of {@link TypeVariable#getBounds()} passed into
1154 * {@link #normalizeUpperBounds}.</p>
1155 *
1156 * @param typeVariable the subject type variable, not {@code null}
8941157 * @return a non-empty array containing the bounds of the type variable.
8951158 */
896 public static Type[] getImplicitBounds(TypeVariable<?> typeVariable) {
897 Type[] bounds = typeVariable.getBounds();
1159 public static Type[] getImplicitBounds(final TypeVariable<?> typeVariable) {
1160 Validate.notNull(typeVariable, "typeVariable is null");
1161 final Type[] bounds = typeVariable.getBounds();
8981162
8991163 return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
9001164 }
9011165
9021166 /**
903 * <p> Returns an array containing the sole value of {@link Object} if
1167 * <p>Returns an array containing the sole value of {@link Object} if
9041168 * {@link WildcardType#getUpperBounds()} returns an empty array. Otherwise,
905 * it returns the result of <code>WildcardType.getUpperBounds()</code>
906 * passed into {@link #normalizeUpperBounds}. </p>
907 *
908 * @param wildcardType the subject wildcard type
1169 * it returns the result of {@link WildcardType#getUpperBounds()}
1170 * passed into {@link #normalizeUpperBounds}.</p>
1171 *
1172 * @param wildcardType the subject wildcard type, not {@code null}
9091173 * @return a non-empty array containing the upper bounds of the wildcard
9101174 * type.
9111175 */
912 public static Type[] getImplicitUpperBounds(WildcardType wildcardType) {
913 Type[] bounds = wildcardType.getUpperBounds();
1176 public static Type[] getImplicitUpperBounds(final WildcardType wildcardType) {
1177 Validate.notNull(wildcardType, "wildcardType is null");
1178 final Type[] bounds = wildcardType.getUpperBounds();
9141179
9151180 return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
9161181 }
9171182
9181183 /**
919 * <p> Returns an array containing a single value of <code>null</code> if
1184 * <p>Returns an array containing a single value of {@code null} if
9201185 * {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise,
921 * it returns the result of <code>WildcardType.getLowerBounds()</code>. </p>
922 *
923 * @param wildcardType the subject wildcard type
1186 * it returns the result of {@link WildcardType#getLowerBounds()}.</p>
1187 *
1188 * @param wildcardType the subject wildcard type, not {@code null}
9241189 * @return a non-empty array containing the lower bounds of the wildcard
9251190 * type.
9261191 */
927 public static Type[] getImplicitLowerBounds(WildcardType wildcardType) {
928 Type[] bounds = wildcardType.getLowerBounds();
1192 public static Type[] getImplicitLowerBounds(final WildcardType wildcardType) {
1193 Validate.notNull(wildcardType, "wildcardType is null");
1194 final Type[] bounds = wildcardType.getLowerBounds();
9291195
9301196 return bounds.length == 0 ? new Type[] { null } : bounds;
9311197 }
9321198
9331199 /**
934 * <p> Determines whether or not specified types satisfy the bounds of their
1200 * <p>Determines whether or not specified types satisfy the bounds of their
9351201 * mapped type variables. When a type parameter extends another (such as
936 * <code><T, S extends T></code>), uses another as a type parameter (such as
937 * <code><T, S extends Comparable<T></code>), or otherwise depends on
1202 * {@code <T, S extends T>}), uses another as a type parameter (such as
1203 * {@code <T, S extends Comparable>>}), or otherwise depends on
9381204 * another type variable to be specified, the dependencies must be included
939 * in <code>typeVarAssigns</code>. </p>
1205 * in {@code typeVarAssigns}.</p>
9401206 *
9411207 * @param typeVarAssigns specifies the potential types to be assigned to the
942 * type variables.
1208 * type variables, not {@code null}.
9431209 * @return whether or not the types can be assigned to their respective type
9441210 * variables.
9451211 */
946 public static boolean typesSatisfyVariables(Map<TypeVariable<?>, Type> typeVarAssigns) {
1212 public static boolean typesSatisfyVariables(final Map<TypeVariable<?>, Type> typeVarAssigns) {
1213 Validate.notNull(typeVarAssigns, "typeVarAssigns is null");
9471214 // all types must be assignable to all the bounds of the their mapped
9481215 // type variable.
949 for (Map.Entry<TypeVariable<?>, Type> entry : typeVarAssigns.entrySet()) {
950 TypeVariable<?> typeVar = entry.getKey();
951 Type type = entry.getValue();
952
953 for (Type bound : getImplicitBounds(typeVar)) {
1216 for (final Map.Entry<TypeVariable<?>, Type> entry : typeVarAssigns.entrySet()) {
1217 final TypeVariable<?> typeVar = entry.getKey();
1218 final Type type = entry.getValue();
1219
1220 for (final Type bound : getImplicitBounds(typeVar)) {
9541221 if (!isAssignable(type, substituteTypeVariables(bound, typeVarAssigns),
9551222 typeVarAssigns)) {
9561223 return false;
9571224 }
9581225 }
9591226 }
960
9611227 return true;
9621228 }
9631229
9641230 /**
965 * <p> Transforms the passed in type to a {@code Class} object. Type-checking method of convenience. </p>
1231 * <p>Transforms the passed in type to a {@link Class} object. Type-checking method of convenience.</p>
9661232 *
9671233 * @param parameterizedType the type to be converted
9681234 * @return the corresponding {@code Class} object
9691235 * @throws IllegalStateException if the conversion fails
9701236 */
971 private static Class<?> getRawType(ParameterizedType parameterizedType) {
972 Type rawType = parameterizedType.getRawType();
1237 private static Class<?> getRawType(final ParameterizedType parameterizedType) {
1238 final Type rawType = parameterizedType.getRawType();
9731239
9741240 // check if raw type is a Class object
9751241 // not currently necessary, but since the return type is Type instead of
9841250 }
9851251
9861252 /**
987 * <p> Get the raw type of a Java type, given its context. Primarily for use
1253 * <p>Get the raw type of a Java type, given its context. Primarily for use
9881254 * with {@link TypeVariable}s and {@link GenericArrayType}s, or when you do
989 * not know the runtime type of <code>type</code>: if you know you have a
1255 * not know the runtime type of {@code type}: if you know you have a
9901256 * {@link Class} instance, it is already raw; if you know you have a
991 * {@link ParameterizedType}, its raw type is only a method call away. </p>
1257 * {@link ParameterizedType}, its raw type is only a method call away.</p>
9921258 *
9931259 * @param type to resolve
9941260 * @param assigningType type to be resolved against
995 * @return the resolved <code>Class</code> object or <code>null</code> if
1261 * @return the resolved {@link Class} object or {@code null} if
9961262 * the type could not be resolved
9971263 */
998 public static Class<?> getRawType(Type type, Type assigningType) {
1264 public static Class<?> getRawType(final Type type, final Type assigningType) {
9991265 if (type instanceof Class<?>) {
10001266 // it is raw, no problem
10011267 return (Class<?>) type;
10121278 }
10131279
10141280 // get the entity declaring this type variable
1015 Object genericDeclaration = ((TypeVariable<?>) type).getGenericDeclaration();
1281 final Object genericDeclaration = ((TypeVariable<?>) type).getGenericDeclaration();
10161282
10171283 // can't get the raw type of a method- or constructor-declared type
10181284 // variable
10221288
10231289 // get the type arguments for the declaring class/interface based
10241290 // on the enclosing type
1025 Map<TypeVariable<?>, Type> typeVarAssigns = getTypeArguments(assigningType,
1291 final Map<TypeVariable<?>, Type> typeVarAssigns = getTypeArguments(assigningType,
10261292 (Class<?>) genericDeclaration);
10271293
10281294 // enclosingType has to be a subclass (or subinterface) of the
10321298 }
10331299
10341300 // get the argument assigned to this type variable
1035 Type typeArgument = typeVarAssigns.get(type);
1301 final Type typeArgument = typeVarAssigns.get(type);
10361302
10371303 if (typeArgument == null) {
10381304 return null;
10441310
10451311 if (type instanceof GenericArrayType) {
10461312 // get raw component type
1047 Class<?> rawComponentType = getRawType(((GenericArrayType) type)
1313 final Class<?> rawComponentType = getRawType(((GenericArrayType) type)
10481314 .getGenericComponentType(), assigningType);
10491315
10501316 // create array type from raw component type and return its class
10621328 /**
10631329 * Learn whether the specified type denotes an array type.
10641330 * @param type the type to be checked
1065 * @return <code>true</code> if <code>type</code> is an array class or a {@link GenericArrayType}.
1066 */
1067 public static boolean isArrayType(Type type) {
1331 * @return {@code true} if {@code type} is an array class or a {@link GenericArrayType}.
1332 */
1333 public static boolean isArrayType(final Type type) {
10681334 return type instanceof GenericArrayType || type instanceof Class<?> && ((Class<?>) type).isArray();
10691335 }
10701336
10711337 /**
1072 * Get the array component type of <code>type</code>.
1338 * Get the array component type of {@code type}.
10731339 * @param type the type to be checked
10741340 * @return component type or null if type is not an array type
10751341 */
1076 public static Type getArrayComponentType(Type type) {
1342 public static Type getArrayComponentType(final Type type) {
10771343 if (type instanceof Class<?>) {
1078 Class<?> clazz = (Class<?>) type;
1344 final Class<?> clazz = (Class<?>) type;
10791345 return clazz.isArray() ? clazz.getComponentType() : null;
10801346 }
10811347 if (type instanceof GenericArrayType) {
10841350 return null;
10851351 }
10861352
1353 /**
1354 * Get a type representing {@code type} with variable assignments "unrolled."
1355 *
1356 * @param typeArguments as from {@link TypeUtils#getTypeArguments(Type, Class)}
1357 * @param type the type to unroll variable assignments for
1358 * @return Type
1359 * @since 3.2
1360 */
1361 public static Type unrollVariables(Map<TypeVariable<?>, Type> typeArguments, final Type type) {
1362 if (typeArguments == null) {
1363 typeArguments = Collections.<TypeVariable<?>, Type> emptyMap();
1364 }
1365 if (containsTypeVariables(type)) {
1366 if (type instanceof TypeVariable<?>) {
1367 return unrollVariables(typeArguments, typeArguments.get(type));
1368 }
1369 if (type instanceof ParameterizedType) {
1370 final ParameterizedType p = (ParameterizedType) type;
1371 final Map<TypeVariable<?>, Type> parameterizedTypeArguments;
1372 if (p.getOwnerType() == null) {
1373 parameterizedTypeArguments = typeArguments;
1374 } else {
1375 parameterizedTypeArguments = new HashMap<TypeVariable<?>, Type>(typeArguments);
1376 parameterizedTypeArguments.putAll(TypeUtils.getTypeArguments(p));
1377 }
1378 final Type[] args = p.getActualTypeArguments();
1379 for (int i = 0; i < args.length; i++) {
1380 final Type unrolled = unrollVariables(parameterizedTypeArguments, args[i]);
1381 if (unrolled != null) {
1382 args[i] = unrolled;
1383 }
1384 }
1385 return parameterizeWithOwner(p.getOwnerType(), (Class<?>) p.getRawType(), args);
1386 }
1387 if (type instanceof WildcardType) {
1388 final WildcardType wild = (WildcardType) type;
1389 return wildcardType().withUpperBounds(unrollBounds(typeArguments, wild.getUpperBounds()))
1390 .withLowerBounds(unrollBounds(typeArguments, wild.getLowerBounds())).build();
1391 }
1392 }
1393 return type;
1394 }
1395
1396 /**
1397 * Local helper method to unroll variables in a type bounds array.
1398 *
1399 * @param typeArguments assignments {@link Map}
1400 * @param bounds in which to expand variables
1401 * @return {@code bounds} with any variables reassigned
1402 * @since 3.2
1403 */
1404 private static Type[] unrollBounds(final Map<TypeVariable<?>, Type> typeArguments, final Type[] bounds) {
1405 Type[] result = bounds;
1406 int i = 0;
1407 for (; i < result.length; i++) {
1408 final Type unrolled = unrollVariables(typeArguments, result[i]);
1409 if (unrolled == null) {
1410 result = ArrayUtils.remove(result, i--);
1411 } else {
1412 result[i] = unrolled;
1413 }
1414 }
1415 return result;
1416 }
1417
1418 /**
1419 * Learn, recursively, whether any of the type parameters associated with {@code type} are bound to variables.
1420 *
1421 * @param type the type to check for type variables
1422 * @return boolean
1423 * @since 3.2
1424 */
1425 public static boolean containsTypeVariables(Type type) {
1426 if (type instanceof TypeVariable<?>) {
1427 return true;
1428 }
1429 if (type instanceof Class<?>) {
1430 return ((Class<?>) type).getTypeParameters().length > 0;
1431 }
1432 if (type instanceof ParameterizedType) {
1433 for (Type arg : ((ParameterizedType) type).getActualTypeArguments()) {
1434 if (containsTypeVariables(arg)) {
1435 return true;
1436 }
1437 }
1438 return false;
1439 }
1440 if (type instanceof WildcardType) {
1441 WildcardType wild = (WildcardType) type;
1442 return containsTypeVariables(TypeUtils.getImplicitLowerBounds(wild)[0])
1443 || containsTypeVariables(TypeUtils.getImplicitUpperBounds(wild)[0]);
1444 }
1445 return false;
1446 }
1447
1448 /**
1449 * Create a parameterized type instance.
1450 *
1451 * @param raw the raw class to create a parameterized type instance for
1452 * @param typeArguments the types used for parameterization
1453 * @return {@link ParameterizedType}
1454 * @since 3.2
1455 */
1456 public static final ParameterizedType parameterize(final Class<?> raw, final Type... typeArguments) {
1457 return parameterizeWithOwner(null, raw, typeArguments);
1458 }
1459
1460 /**
1461 * Create a parameterized type instance.
1462 *
1463 * @param raw the raw class to create a parameterized type instance for
1464 * @param typeArgMappings the mapping used for parameterization
1465 * @return {@link ParameterizedType}
1466 * @since 3.2
1467 */
1468 public static final ParameterizedType parameterize(final Class<?> raw,
1469 final Map<TypeVariable<?>, Type> typeArgMappings) {
1470 Validate.notNull(raw, "raw class is null");
1471 Validate.notNull(typeArgMappings, "typeArgMappings is null");
1472 return parameterizeWithOwner(null, raw, extractTypeArgumentsFrom(typeArgMappings, raw.getTypeParameters()));
1473 }
1474
1475 /**
1476 * Create a parameterized type instance.
1477 *
1478 * @param owner the owning type
1479 * @param raw the raw class to create a parameterized type instance for
1480 * @param typeArguments the types used for parameterization
1481 *
1482 * @return {@link ParameterizedType}
1483 * @since 3.2
1484 */
1485 public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class<?> raw,
1486 final Type... typeArguments) {
1487 Validate.notNull(raw, "raw class is null");
1488 final Type useOwner;
1489 if (raw.getEnclosingClass() == null) {
1490 Validate.isTrue(owner == null, "no owner allowed for top-level %s", raw);
1491 useOwner = null;
1492 } else if (owner == null) {
1493 useOwner = raw.getEnclosingClass();
1494 } else {
1495 Validate.isTrue(TypeUtils.isAssignable(owner, raw.getEnclosingClass()),
1496 "%s is invalid owner type for parameterized %s", owner, raw);
1497 useOwner = owner;
1498 }
1499 Validate.noNullElements(typeArguments, "null type argument at index %s");
1500 Validate.isTrue(raw.getTypeParameters().length == typeArguments.length,
1501 "invalid number of type parameters specified: expected %s, got %s", raw.getTypeParameters().length,
1502 typeArguments.length);
1503
1504 return new ParameterizedTypeImpl(raw, useOwner, typeArguments);
1505 }
1506
1507 /**
1508 * Create a parameterized type instance.
1509 *
1510 * @param owner the owning type
1511 * @param raw the raw class to create a parameterized type instance for
1512 * @param typeArgMappings the mapping used for parameterization
1513 * @return {@link ParameterizedType}
1514 * @since 3.2
1515 */
1516 public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class<?> raw,
1517 final Map<TypeVariable<?>, Type> typeArgMappings) {
1518 Validate.notNull(raw, "raw class is null");
1519 Validate.notNull(typeArgMappings, "typeArgMappings is null");
1520 return parameterizeWithOwner(owner, raw, extractTypeArgumentsFrom(typeArgMappings, raw.getTypeParameters()));
1521 }
1522
1523 /**
1524 * Helper method to establish the formal parameters for a parameterized type.
1525 * @param mappings map containing the assignements
1526 * @param variables expected map keys
1527 * @return array of map values corresponding to specified keys
1528 */
1529 private static Type[] extractTypeArgumentsFrom(Map<TypeVariable<?>, Type> mappings, TypeVariable<?>[] variables) {
1530 final Type[] result = new Type[variables.length];
1531 int index = 0;
1532 for (TypeVariable<?> var : variables) {
1533 Validate.isTrue(mappings.containsKey(var), "missing argument mapping for %s", toString(var));
1534 result[index++] = mappings.get(var);
1535 }
1536 return result;
1537 }
1538
1539 /**
1540 * Get a {@link WildcardTypeBuilder}.
1541 * @return {@link WildcardTypeBuilder}
1542 * @since 3.2
1543 */
1544 public static WildcardTypeBuilder wildcardType() {
1545 return new WildcardTypeBuilder();
1546 }
1547
1548 /**
1549 * Create a generic array type instance.
1550 *
1551 * @param componentType the type of the elements of the array. For example the component type of {@code boolean[]}
1552 * is {@code boolean}
1553 * @return {@link GenericArrayType}
1554 * @since 3.2
1555 */
1556 public static GenericArrayType genericArrayType(final Type componentType) {
1557 return new GenericArrayTypeImpl(Validate.notNull(componentType, "componentType is null"));
1558 }
1559
1560 /**
1561 * Check equality of types.
1562 *
1563 * @param t1 the first type
1564 * @param t2 the second type
1565 * @return boolean
1566 * @since 3.2
1567 */
1568 public static boolean equals(Type t1, Type t2) {
1569 if (ObjectUtils.equals(t1, t2)) {
1570 return true;
1571 }
1572 if (t1 instanceof ParameterizedType) {
1573 return equals((ParameterizedType) t1, t2);
1574 }
1575 if (t1 instanceof GenericArrayType) {
1576 return equals((GenericArrayType) t1, t2);
1577 }
1578 if (t1 instanceof WildcardType) {
1579 return equals((WildcardType) t1, t2);
1580 }
1581 return false;
1582 }
1583
1584 /**
1585 * Learn whether {@code t} equals {@code p}.
1586 * @param p LHS
1587 * @param t RHS
1588 * @return boolean
1589 * @since 3.2
1590 */
1591 private static boolean equals(ParameterizedType p, Type t) {
1592 if (t instanceof ParameterizedType) {
1593 final ParameterizedType other = (ParameterizedType) t;
1594 if (equals(p.getRawType(), other.getRawType()) && equals(p.getOwnerType(), other.getOwnerType())) {
1595 return equals(p.getActualTypeArguments(), other.getActualTypeArguments());
1596 }
1597 }
1598 return false;
1599 }
1600
1601 /**
1602 * Learn whether {@code t} equals {@code a}.
1603 * @param a LHS
1604 * @param t RHS
1605 * @return boolean
1606 * @since 3.2
1607 */
1608 private static boolean equals(GenericArrayType a, Type t) {
1609 return t instanceof GenericArrayType
1610 && equals(a.getGenericComponentType(), ((GenericArrayType) t).getGenericComponentType());
1611 }
1612
1613 /**
1614 * Learn whether {@code t} equals {@code w}.
1615 * @param w LHS
1616 * @param t RHS
1617 * @return boolean
1618 * @since 3.2
1619 */
1620 private static boolean equals(WildcardType w, Type t) {
1621 if (t instanceof WildcardType) {
1622 final WildcardType other = (WildcardType) t;
1623 return equals(w.getLowerBounds(), other.getLowerBounds())
1624 && equals(TypeUtils.getImplicitUpperBounds(w), TypeUtils.getImplicitUpperBounds(other));
1625 }
1626 return true;
1627 }
1628
1629 /**
1630 * Learn whether {@code t1} equals {@code t2}.
1631 * @param t1 LHS
1632 * @param t2 RHS
1633 * @return boolean
1634 * @since 3.2
1635 */
1636 private static boolean equals(Type[] t1, Type[] t2) {
1637 if (t1.length == t2.length) {
1638 for (int i = 0; i < t1.length; i++) {
1639 if (!equals(t1[i], t2[i])) {
1640 return false;
1641 }
1642 }
1643 return true;
1644 }
1645 return false;
1646 }
1647
1648 /**
1649 * Present a given type as a Java-esque String.
1650 *
1651 * @param type the type to create a String representation for, not {@code null}
1652 * @return String
1653 * @since 3.2
1654 */
1655 public static String toString(Type type) {
1656 Validate.notNull(type);
1657 if (type instanceof Class<?>) {
1658 return classToString((Class<?>) type);
1659 }
1660 if (type instanceof ParameterizedType) {
1661 return parameterizedTypeToString((ParameterizedType) type);
1662 }
1663 if (type instanceof WildcardType) {
1664 return wildcardTypeToString((WildcardType) type);
1665 }
1666 if (type instanceof TypeVariable<?>) {
1667 return typeVariableToString((TypeVariable<?>) type);
1668 }
1669 if (type instanceof GenericArrayType) {
1670 return genericArrayTypeToString((GenericArrayType) type);
1671 }
1672 throw new IllegalArgumentException(ObjectUtils.identityToString(type));
1673 }
1674
1675 /**
1676 * Format a {@link TypeVariable} including its {@link GenericDeclaration}.
1677 *
1678 * @param var the type variable to create a String representation for, not {@code null}
1679 * @return String
1680 * @since 3.2
1681 */
1682 public static String toLongString(TypeVariable<?> var) {
1683 Validate.notNull(var, "var is null");
1684 final StringBuilder buf = new StringBuilder();
1685 final GenericDeclaration d = ((TypeVariable<?>) var).getGenericDeclaration();
1686 if (d instanceof Class<?>) {
1687 Class<?> c = (Class<?>) d;
1688 while (true) {
1689 if (c.getEnclosingClass() == null) {
1690 buf.insert(0, c.getName());
1691 break;
1692 }
1693 buf.insert(0, c.getSimpleName()).insert(0, '.');
1694 c = c.getEnclosingClass();
1695 }
1696 } else if (d instanceof Type) {// not possible as of now
1697 buf.append(toString((Type) d));
1698 } else {
1699 buf.append(d);
1700 }
1701 return buf.append(':').append(typeVariableToString(var)).toString();
1702 }
1703
1704 /**
1705 * Wrap the specified {@link Type} in a {@link Typed} wrapper.
1706 *
1707 * @param <T> inferred generic type
1708 * @param type to wrap
1709 * @return Typed&lt;T&gt;
1710 * @since 3.2
1711 */
1712 public static <T> Typed<T> wrap(final Type type) {
1713 return new Typed<T>() {
1714 @Override
1715 public Type getType() {
1716 return type;
1717 }
1718 };
1719 }
1720
1721 /**
1722 * Wrap the specified {@link Class} in a {@link Typed} wrapper.
1723 *
1724 * @param <T> generic type
1725 * @param type to wrap
1726 * @return Typed&lt;T&gt;
1727 * @since 3.2
1728 */
1729 public static <T> Typed<T> wrap(final Class<T> type) {
1730 return TypeUtils.<T> wrap((Type) type);
1731 }
1732
1733 /**
1734 * Format a {@link Class} as a {@link String}.
1735 * @param c {@code Class} to format
1736 * @return String
1737 * @since 3.2
1738 */
1739 private static String classToString(Class<?> c) {
1740 final StringBuilder buf = new StringBuilder();
1741
1742 if (c.getEnclosingClass() != null) {
1743 buf.append(classToString(c.getEnclosingClass())).append('.').append(c.getSimpleName());
1744 } else {
1745 buf.append(c.getName());
1746 }
1747 if (c.getTypeParameters().length > 0) {
1748 buf.append('<');
1749 appendAllTo(buf, ", ", c.getTypeParameters());
1750 buf.append('>');
1751 }
1752 return buf.toString();
1753 }
1754
1755 /**
1756 * Format a {@link TypeVariable} as a {@link String}.
1757 * @param v {@code TypeVariable} to format
1758 * @return String
1759 * @since 3.2
1760 */
1761 private static String typeVariableToString(TypeVariable<?> v) {
1762 final StringBuilder buf = new StringBuilder(v.getName());
1763 final Type[] bounds = v.getBounds();
1764 if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(bounds[0]))) {
1765 buf.append(" extends ");
1766 appendAllTo(buf, " & ", v.getBounds());
1767 }
1768 return buf.toString();
1769 }
1770
1771 /**
1772 * Format a {@link ParameterizedType} as a {@link String}.
1773 * @param p {@code ParameterizedType} to format
1774 * @return String
1775 * @since 3.2
1776 */
1777 private static String parameterizedTypeToString(ParameterizedType p) {
1778 final StringBuilder buf = new StringBuilder();
1779
1780 final Type useOwner = p.getOwnerType();
1781 final Class<?> raw = (Class<?>) p.getRawType();
1782 final Type[] typeArguments = p.getActualTypeArguments();
1783 if (useOwner == null) {
1784 buf.append(raw.getName());
1785 } else {
1786 if (useOwner instanceof Class<?>) {
1787 buf.append(((Class<?>) useOwner).getName());
1788 } else {
1789 buf.append(useOwner.toString());
1790 }
1791 buf.append('.').append(raw.getSimpleName());
1792 }
1793
1794 appendAllTo(buf.append('<'), ", ", typeArguments).append('>');
1795 return buf.toString();
1796 }
1797
1798 /**
1799 * Format a {@link WildcardType} as a {@link String}.
1800 * @param w {@code WildcardType} to format
1801 * @return String
1802 * @since 3.2
1803 */
1804 private static String wildcardTypeToString(WildcardType w) {
1805 final StringBuilder buf = new StringBuilder().append('?');
1806 final Type[] lowerBounds = w.getLowerBounds();
1807 final Type[] upperBounds = w.getUpperBounds();
1808 if (lowerBounds.length > 0) {
1809 appendAllTo(buf.append(" super "), " & ", lowerBounds);
1810 } else if (!(upperBounds.length == 1 && Object.class.equals(upperBounds[0]))) {
1811 appendAllTo(buf.append(" extends "), " & ", upperBounds);
1812 }
1813 return buf.toString();
1814 }
1815
1816 /**
1817 * Format a {@link GenericArrayType} as a {@link String}.
1818 * @param g {@code GenericArrayType} to format
1819 * @return String
1820 * @since 3.2
1821 */
1822 private static String genericArrayTypeToString(GenericArrayType g) {
1823 return String.format("%s[]", toString(g.getGenericComponentType()));
1824 }
1825
1826 /**
1827 * Append {@code types} to @{code buf} with separator {@code sep}.
1828 * @param buf destination
1829 * @param sep separator
1830 * @param types to append
1831 * @return {@code buf}
1832 * @since 3.2
1833 */
1834 private static StringBuilder appendAllTo(StringBuilder buf, String sep, Type... types) {
1835 Validate.notEmpty(Validate.noNullElements(types));
1836 if (types.length > 0) {
1837 buf.append(toString(types[0]));
1838 for (int i = 1; i < types.length; i++) {
1839 buf.append(sep).append(toString(types[i]));
1840 }
1841 }
1842 return buf;
1843 }
1844
10871845 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect;
17
18 import java.lang.reflect.Type;
19
20 /**
21 * Generalization of "has a type."
22 * @see TypeLiteral
23 * @since 3.2
24 * @version $Id: Typed.java 1552659 2013-12-20 13:35:22Z britter $
25 */
26 public interface Typed<T> {
27
28 /**
29 * Get the {@link Type} represented by this entity.
30 *
31 * @return Type
32 */
33 Type getType();
34 }
2525 * example of use for this would be a webapp where data is taken in one way and
2626 * stored in a database another way.
2727 *
28 * @version $Id: CompositeFormat.java 1088899 2011-04-05 05:31:27Z bayard $
28 * @version $Id: CompositeFormat.java 1436768 2013-01-22 07:07:42Z ggregory $
2929 */
3030 public class CompositeFormat extends Format {
3131
4848 * @param parser implementation
4949 * @param formatter implementation
5050 */
51 public CompositeFormat(Format parser, Format formatter) {
51 public CompositeFormat(final Format parser, final Format formatter) {
5252 this.parser = parser;
5353 this.formatter = formatter;
5454 }
6262 * @return <code>toAppendTo</code>
6363 * @see Format#format(Object, StringBuffer, FieldPosition)
6464 */
65 @Override
66 public StringBuffer format(Object obj, StringBuffer toAppendTo,
67 FieldPosition pos) {
65 @Override // Therefore has to use StringBuffer
66 public StringBuffer format(final Object obj, final StringBuffer toAppendTo,
67 final FieldPosition pos) {
6868 return formatter.format(obj, toAppendTo, pos);
6969 }
7070
7979 * @see Format#parseObject(String, ParsePosition)
8080 */
8181 @Override
82 public Object parseObject(String source, ParsePosition pos) {
82 public Object parseObject(final String source, final ParsePosition pos) {
8383 return parser.parseObject(source, pos);
8484 }
8585
108108 * @return A reformatted String
109109 * @throws ParseException thrown by parseObject(String) call
110110 */
111 public String reformat(String input) throws ParseException {
111 public String reformat(final String input) throws ParseException {
112112 return format(parseObject(input));
113113 }
114114
6464 * </p>
6565 *
6666 * @since 2.4
67 * @version $Id: ExtendedMessageFormat.java 1199983 2011-11-09 21:41:24Z ggregory $
67 * @version $Id: ExtendedMessageFormat.java 1535547 2013-10-24 20:54:34Z bayard $
6868 */
6969 public class ExtendedMessageFormat extends MessageFormat {
7070 private static final long serialVersionUID = -2362048321261811743L;
8686 * @param pattern the pattern to use, not null
8787 * @throws IllegalArgumentException in case of a bad pattern.
8888 */
89 public ExtendedMessageFormat(String pattern) {
89 public ExtendedMessageFormat(final String pattern) {
9090 this(pattern, Locale.getDefault());
9191 }
9292
9797 * @param locale the locale to use, not null
9898 * @throws IllegalArgumentException in case of a bad pattern.
9999 */
100 public ExtendedMessageFormat(String pattern, Locale locale) {
100 public ExtendedMessageFormat(final String pattern, final Locale locale) {
101101 this(pattern, locale, null);
102102 }
103103
108108 * @param registry the registry of format factories, may be null
109109 * @throws IllegalArgumentException in case of a bad pattern.
110110 */
111 public ExtendedMessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) {
111 public ExtendedMessageFormat(final String pattern, final Map<String, ? extends FormatFactory> registry) {
112112 this(pattern, Locale.getDefault(), registry);
113113 }
114114
120120 * @param registry the registry of format factories, may be null
121121 * @throws IllegalArgumentException in case of a bad pattern.
122122 */
123 public ExtendedMessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) {
123 public ExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry) {
124124 super(DUMMY_PATTERN);
125125 setLocale(locale);
126126 this.registry = registry;
141141 * @param pattern String
142142 */
143143 @Override
144 public final void applyPattern(String pattern) {
144 public final void applyPattern(final String pattern) {
145145 if (registry == null) {
146146 super.applyPattern(pattern);
147147 toPattern = super.toPattern();
148148 return;
149149 }
150 ArrayList<Format> foundFormats = new ArrayList<Format>();
151 ArrayList<String> foundDescriptions = new ArrayList<String>();
152 StringBuilder stripCustom = new StringBuilder(pattern.length());
153
154 ParsePosition pos = new ParsePosition(0);
155 char[] c = pattern.toCharArray();
150 final ArrayList<Format> foundFormats = new ArrayList<Format>();
151 final ArrayList<String> foundDescriptions = new ArrayList<String>();
152 final StringBuilder stripCustom = new StringBuilder(pattern.length());
153
154 final ParsePosition pos = new ParsePosition(0);
155 final char[] c = pattern.toCharArray();
156156 int fmtCount = 0;
157157 while (pos.getIndex() < pattern.length()) {
158158 switch (c[pos.getIndex()]) {
162162 case START_FE:
163163 fmtCount++;
164164 seekNonWs(pattern, pos);
165 int start = pos.getIndex();
166 int index = readArgumentIndex(pattern, next(pos));
165 final int start = pos.getIndex();
166 final int index = readArgumentIndex(pattern, next(pos));
167167 stripCustom.append(START_FE).append(index);
168168 seekNonWs(pattern, pos);
169169 Format format = null;
193193 super.applyPattern(stripCustom.toString());
194194 toPattern = insertFormats(super.toPattern(), foundDescriptions);
195195 if (containsElements(foundFormats)) {
196 Format[] origFormats = getFormats();
196 final Format[] origFormats = getFormats();
197197 // only loop over what we know we have, as MessageFormat on Java 1.3
198198 // seems to provide an extra format element:
199199 int i = 0;
200 for (Iterator<Format> it = foundFormats.iterator(); it.hasNext(); i++) {
201 Format f = it.next();
200 for (final Iterator<Format> it = foundFormats.iterator(); it.hasNext(); i++) {
201 final Format f = it.next();
202202 if (f != null) {
203203 origFormats[i] = f;
204204 }
215215 * @throws UnsupportedOperationException
216216 */
217217 @Override
218 public void setFormat(int formatElementIndex, Format newFormat) {
218 public void setFormat(final int formatElementIndex, final Format newFormat) {
219219 throw new UnsupportedOperationException();
220220 }
221221
227227 * @throws UnsupportedOperationException
228228 */
229229 @Override
230 public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) {
230 public void setFormatByArgumentIndex(final int argumentIndex, final Format newFormat) {
231231 throw new UnsupportedOperationException();
232232 }
233233
238238 * @throws UnsupportedOperationException
239239 */
240240 @Override
241 public void setFormats(Format[] newFormats) {
241 public void setFormats(final Format[] newFormats) {
242242 throw new UnsupportedOperationException();
243243 }
244244
249249 * @throws UnsupportedOperationException
250250 */
251251 @Override
252 public void setFormatsByArgumentIndex(Format[] newFormats) {
252 public void setFormatsByArgumentIndex(final Format[] newFormats) {
253253 throw new UnsupportedOperationException();
254254 }
255255
260260 * @return true if this object equals the other, otherwise false
261261 */
262262 @Override
263 public boolean equals(Object obj) {
263 public boolean equals(final Object obj) {
264264 if (obj == this) {
265265 return true;
266266 }
273273 if (ObjectUtils.notEqual(getClass(), obj.getClass())) {
274274 return false;
275275 }
276 ExtendedMessageFormat rhs = (ExtendedMessageFormat)obj;
276 final ExtendedMessageFormat rhs = (ExtendedMessageFormat)obj;
277277 if (ObjectUtils.notEqual(toPattern, rhs.toPattern)) {
278278 return false;
279279 }
302302 * @param desc String
303303 * @return Format
304304 */
305 private Format getFormat(String desc) {
305 private Format getFormat(final String desc) {
306306 if (registry != null) {
307307 String name = desc;
308308 String args = null;
309 int i = desc.indexOf(START_FMT);
309 final int i = desc.indexOf(START_FMT);
310310 if (i > 0) {
311311 name = desc.substring(0, i).trim();
312312 args = desc.substring(i + 1).trim();
313313 }
314 FormatFactory factory = registry.get(name);
314 final FormatFactory factory = registry.get(name);
315315 if (factory != null) {
316316 return factory.getFormat(name, args, getLocale());
317317 }
326326 * @param pos current parse position
327327 * @return argument index
328328 */
329 private int readArgumentIndex(String pattern, ParsePosition pos) {
330 int start = pos.getIndex();
329 private int readArgumentIndex(final String pattern, final ParsePosition pos) {
330 final int start = pos.getIndex();
331331 seekNonWs(pattern, pos);
332 StringBuffer result = new StringBuffer();
332 final StringBuilder result = new StringBuilder();
333333 boolean error = false;
334334 for (; !error && pos.getIndex() < pattern.length(); next(pos)) {
335335 char c = pattern.charAt(pos.getIndex());
344344 if ((c == START_FMT || c == END_FE) && result.length() > 0) {
345345 try {
346346 return Integer.parseInt(result.toString());
347 } catch (NumberFormatException e) { // NOPMD
347 } catch (final NumberFormatException e) { // NOPMD
348348 // we've already ensured only digits, so unless something
349349 // outlandishly large was specified we should be okay.
350350 }
368368 * @param pos current parse position
369369 * @return Format description String
370370 */
371 private String parseFormatDescription(String pattern, ParsePosition pos) {
372 int start = pos.getIndex();
371 private String parseFormatDescription(final String pattern, final ParsePosition pos) {
372 final int start = pos.getIndex();
373373 seekNonWs(pattern, pos);
374 int text = pos.getIndex();
374 final int text = pos.getIndex();
375375 int depth = 1;
376376 for (; pos.getIndex() < pattern.length(); next(pos)) {
377377 switch (pattern.charAt(pos.getIndex())) {
400400 * @param customPatterns The custom patterns to re-insert, if any
401401 * @return full pattern
402402 */
403 private String insertFormats(String pattern, ArrayList<String> customPatterns) {
403 private String insertFormats(final String pattern, final ArrayList<String> customPatterns) {
404404 if (!containsElements(customPatterns)) {
405405 return pattern;
406406 }
407 StringBuilder sb = new StringBuilder(pattern.length() * 2);
408 ParsePosition pos = new ParsePosition(0);
407 final StringBuilder sb = new StringBuilder(pattern.length() * 2);
408 final ParsePosition pos = new ParsePosition(0);
409409 int fe = -1;
410410 int depth = 0;
411411 while (pos.getIndex() < pattern.length()) {
412 char c = pattern.charAt(pos.getIndex());
412 final char c = pattern.charAt(pos.getIndex());
413413 switch (c) {
414414 case QUOTE:
415415 appendQuotedString(pattern, pos, sb, false);
416416 break;
417417 case START_FE:
418418 depth++;
419 sb.append(START_FE).append(readArgumentIndex(pattern, next(pos)));
420 // do not look for custom patterns when they are embedded, e.g. in a choice
419421 if (depth == 1) {
420422 fe++;
421 sb.append(START_FE).append(
422 readArgumentIndex(pattern, next(pos)));
423 String customPattern = customPatterns.get(fe);
423 final String customPattern = customPatterns.get(fe);
424424 if (customPattern != null) {
425425 sb.append(START_FMT).append(customPattern);
426426 }
443443 * @param pattern String to read
444444 * @param pos current position
445445 */
446 private void seekNonWs(String pattern, ParsePosition pos) {
446 private void seekNonWs(final String pattern, final ParsePosition pos) {
447447 int len = 0;
448 char[] buffer = pattern.toCharArray();
448 final char[] buffer = pattern.toCharArray();
449449 do {
450450 len = StrMatcher.splitMatcher().isMatch(buffer, pos.getIndex());
451451 pos.setIndex(pos.getIndex() + len);
458458 * @param pos ParsePosition
459459 * @return <code>pos</code>
460460 */
461 private ParsePosition next(ParsePosition pos) {
461 private ParsePosition next(final ParsePosition pos) {
462462 pos.setIndex(pos.getIndex() + 1);
463463 return pos;
464464 }
469469 *
470470 * @param pattern pattern to parse
471471 * @param pos current parse position
472 * @param appendTo optional StringBuffer to append
472 * @param appendTo optional StringBuilder to append
473473 * @param escapingOn whether to process escaped quotes
474474 * @return <code>appendTo</code>
475475 */
476 private StringBuilder appendQuotedString(String pattern, ParsePosition pos,
477 StringBuilder appendTo, boolean escapingOn) {
478 int start = pos.getIndex();
479 char[] c = pattern.toCharArray();
476 private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos,
477 final StringBuilder appendTo, final boolean escapingOn) {
478 final int start = pos.getIndex();
479 final char[] c = pattern.toCharArray();
480480 if (escapingOn && c[start] == QUOTE) {
481481 next(pos);
482482 return appendTo == null ? null : appendTo.append(QUOTE);
510510 * @param pos current parse position
511511 * @param escapingOn whether to process escaped quotes
512512 */
513 private void getQuotedString(String pattern, ParsePosition pos,
514 boolean escapingOn) {
513 private void getQuotedString(final String pattern, final ParsePosition pos,
514 final boolean escapingOn) {
515515 appendQuotedString(pattern, pos, null, escapingOn);
516516 }
517517
520520 * @param coll to check
521521 * @return <code>true</code> if some Object was found, <code>false</code> otherwise.
522522 */
523 private boolean containsElements(Collection<?> coll) {
523 private boolean containsElements(final Collection<?> coll) {
524524 if (coll == null || coll.isEmpty()) {
525525 return false;
526526 }
527 for (Object name : coll) {
527 for (final Object name : coll) {
528528 if (name != null) {
529529 return true;
530530 }
3232 * and padding, and is not designed to allow generalised alternate formats.</p>
3333 *
3434 * @since Lang 3.0
35 * @version $Id: FormattableUtils.java 1132390 2011-06-05 12:45:10Z sebb $
35 * @version $Id: FormattableUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3636 */
3737 public class FormattableUtils {
3838
6161 * @param formattable the instance to convert to a string, not null
6262 * @return the resulting string, not null
6363 */
64 public static String toString(Formattable formattable) {
64 public static String toString(final Formattable formattable) {
6565 return String.format(SIMPLEST_FORMAT, formattable);
6666 }
6767
7777 * @param precision the precision of the output, see {@code Formattable}
7878 * @return the {@code formatter} instance, not null
7979 */
80 public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width,
81 int precision) {
80 public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
81 final int precision) {
8282 return append(seq, formatter, flags, width, precision, ' ', null);
8383 }
8484
9494 * @param padChar the pad character to use
9595 * @return the {@code formatter} instance, not null
9696 */
97 public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width,
98 int precision, char padChar) {
97 public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
98 final int precision, final char padChar) {
9999 return append(seq, formatter, flags, width, precision, padChar, null);
100100 }
101101
112112 * empty causes a hard truncation
113113 * @return the {@code formatter} instance, not null
114114 */
115 public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width,
116 int precision, CharSequence ellipsis) {
115 public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
116 final int precision, final CharSequence ellipsis) {
117117 return append(seq, formatter, flags, width, precision, ' ', ellipsis);
118118 }
119119
130130 * empty causes a hard truncation
131131 * @return the {@code formatter} instance, not null
132132 */
133 public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width,
134 int precision, char padChar, CharSequence ellipsis) {
133 public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
134 final int precision, final char padChar, final CharSequence ellipsis) {
135135 Validate.isTrue(ellipsis == null || precision < 0 || ellipsis.length() <= precision,
136136 "Specified ellipsis '%1$s' exceeds precision of %2$s", ellipsis, Integer.valueOf(precision));
137 StringBuilder buf = new StringBuilder(seq);
137 final StringBuilder buf = new StringBuilder(seq);
138138 if (precision >= 0 && precision < seq.length()) {
139 CharSequence _ellipsis = ObjectUtils.defaultIfNull(ellipsis, StringUtils.EMPTY);
139 final CharSequence _ellipsis = ObjectUtils.defaultIfNull(ellipsis, StringUtils.EMPTY);
140140 buf.replace(precision - _ellipsis.length(), seq.length(), _ellipsis.toString());
141141 }
142 boolean leftJustify = (flags & LEFT_JUSTIFY) == LEFT_JUSTIFY;
142 final boolean leftJustify = (flags & LEFT_JUSTIFY) == LEFT_JUSTIFY;
143143 for (int i = buf.length(); i < width; i++) {
144144 buf.insert(leftJustify ? i : 0, padChar);
145145 }
1616 package org.apache.commons.lang3.text;
1717
1818 import java.io.Reader;
19 import java.io.Serializable;
1920 import java.io.Writer;
2021 import java.util.Iterator;
2122 import java.util.List;
2324 import org.apache.commons.lang3.ArrayUtils;
2425 import org.apache.commons.lang3.ObjectUtils;
2526 import org.apache.commons.lang3.SystemUtils;
27 import org.apache.commons.lang3.builder.Builder;
2628
2729 /**
2830 * Builds a string from constituent parts providing a more flexible and powerful API
6769 * the interface.
6870 *
6971 * @since 2.2
70 * @version $Id: StrBuilder.java 1199888 2011-11-09 17:35:01Z ggregory $
72 * @version $Id: StrBuilder.java 1552657 2013-12-20 13:30:16Z britter $
7173 */
72 public class StrBuilder implements CharSequence, Appendable {
74 public class StrBuilder implements CharSequence, Appendable, Serializable, Builder<String> {
7375
7476 /**
7577 * The extra capacity for new builders.
119121 *
120122 * @param str the string to copy, null treated as blank string
121123 */
122 public StrBuilder(String str) {
124 public StrBuilder(final String str) {
123125 super();
124126 if (str == null) {
125127 buffer = new char[CAPACITY];
145147 * @param newLine the new line text, null means use system default
146148 * @return this, to enable chaining
147149 */
148 public StrBuilder setNewLineText(String newLine) {
150 public StrBuilder setNewLineText(final String newLine) {
149151 this.newLine = newLine;
150152 return this;
151153 }
167169 * @return this, to enable chaining
168170 */
169171 public StrBuilder setNullText(String nullText) {
170 if (nullText != null && nullText.length() == 0) {
172 if (nullText != null && nullText.isEmpty()) {
171173 nullText = null;
172174 }
173175 this.nullText = nullText;
180182 *
181183 * @return the length
182184 */
185 @Override
183186 public int length() {
184187 return size;
185188 }
192195 * @return this, to enable chaining
193196 * @throws IndexOutOfBoundsException if the length is negative
194197 */
195 public StrBuilder setLength(int length) {
198 public StrBuilder setLength(final int length) {
196199 if (length < 0) {
197200 throw new StringIndexOutOfBoundsException(length);
198201 }
200203 size = length;
201204 } else if (length > size) {
202205 ensureCapacity(length);
203 int oldEnd = size;
204 int newEnd = length;
206 final int oldEnd = size;
207 final int newEnd = length;
205208 size = length;
206209 for (int i = oldEnd; i < newEnd; i++) {
207210 buffer[i] = '\0';
226229 * @param capacity the capacity to ensure
227230 * @return this, to enable chaining
228231 */
229 public StrBuilder ensureCapacity(int capacity) {
232 public StrBuilder ensureCapacity(final int capacity) {
230233 if (capacity > buffer.length) {
231 char[] old = buffer;
234 final char[] old = buffer;
232235 buffer = new char[capacity * 2];
233236 System.arraycopy(old, 0, buffer, 0, size);
234237 }
242245 */
243246 public StrBuilder minimizeCapacity() {
244247 if (buffer.length > length()) {
245 char[] old = buffer;
248 final char[] old = buffer;
246249 buffer = new char[length()];
247250 System.arraycopy(old, 0, buffer, 0, size);
248251 }
300303 * @return the character at the index
301304 * @throws IndexOutOfBoundsException if the index is invalid
302305 */
303 public char charAt(int index) {
306 @Override
307 public char charAt(final int index) {
304308 if (index < 0 || index >= length()) {
305309 throw new StringIndexOutOfBoundsException(index);
306310 }
317321 * @return this, to enable chaining
318322 * @throws IndexOutOfBoundsException if the index is invalid
319323 */
320 public StrBuilder setCharAt(int index, char ch) {
324 public StrBuilder setCharAt(final int index, final char ch) {
321325 if (index < 0 || index >= length()) {
322326 throw new StringIndexOutOfBoundsException(index);
323327 }
334338 * @return this, to enable chaining
335339 * @throws IndexOutOfBoundsException if the index is invalid
336340 */
337 public StrBuilder deleteCharAt(int index) {
341 public StrBuilder deleteCharAt(final int index) {
338342 if (index < 0 || index >= size) {
339343 throw new StringIndexOutOfBoundsException(index);
340344 }
352356 if (size == 0) {
353357 return ArrayUtils.EMPTY_CHAR_ARRAY;
354358 }
355 char chars[] = new char[size];
359 final char chars[] = new char[size];
356360 System.arraycopy(buffer, 0, chars, 0, size);
357361 return chars;
358362 }
367371 * @throws IndexOutOfBoundsException if startIndex is invalid,
368372 * or if endIndex is invalid (but endIndex greater than size is valid)
369373 */
370 public char[] toCharArray(int startIndex, int endIndex) {
374 public char[] toCharArray(final int startIndex, int endIndex) {
371375 endIndex = validateRange(startIndex, endIndex);
372 int len = endIndex - startIndex;
376 final int len = endIndex - startIndex;
373377 if (len == 0) {
374378 return ArrayUtils.EMPTY_CHAR_ARRAY;
375379 }
376 char chars[] = new char[len];
380 final char chars[] = new char[len];
377381 System.arraycopy(buffer, startIndex, chars, 0, len);
378382 return chars;
379383 }
385389 * @return the input array, unless that was null or too small
386390 */
387391 public char[] getChars(char[] destination) {
388 int len = length();
392 final int len = length();
389393 if (destination == null || destination.length < len) {
390394 destination = new char[len];
391395 }
403407 * @throws NullPointerException if the array is null
404408 * @throws IndexOutOfBoundsException if any index is invalid
405409 */
406 public void getChars(int startIndex, int endIndex, char destination[], int destinationIndex) {
410 public void getChars(final int startIndex, final int endIndex, final char destination[], final int destinationIndex) {
407411 if (startIndex < 0) {
408412 throw new StringIndexOutOfBoundsException(startIndex);
409413 }
453457 * @param obj the object to append
454458 * @return this, to enable chaining
455459 */
456 public StrBuilder append(Object obj) {
460 public StrBuilder append(final Object obj) {
457461 if (obj == null) {
458462 return appendNull();
459463 }
468472 * @return this, to enable chaining
469473 * @since 3.0
470474 */
471 public StrBuilder append(CharSequence seq) {
475 @Override
476 public StrBuilder append(final CharSequence seq) {
472477 if (seq == null) {
473478 return appendNull();
474479 }
485490 * @return this, to enable chaining
486491 * @since 3.0
487492 */
488 public StrBuilder append(CharSequence seq, int startIndex, int length) {
493 @Override
494 public StrBuilder append(final CharSequence seq, final int startIndex, final int length) {
489495 if (seq == null) {
490496 return appendNull();
491497 }
492498 return append(seq.toString(), startIndex, length);
493499 }
494
500
495501 /**
496502 * Appends a string to this string builder.
497503 * Appending null will call {@link #appendNull()}.
499505 * @param str the string to append
500506 * @return this, to enable chaining
501507 */
502 public StrBuilder append(String str) {
508 public StrBuilder append(final String str) {
503509 if (str == null) {
504510 return appendNull();
505511 }
506 int strLen = str.length();
512 final int strLen = str.length();
507513 if (strLen > 0) {
508 int len = length();
514 final int len = length();
509515 ensureCapacity(len + strLen);
510516 str.getChars(0, strLen, buffer, len);
511517 size += strLen;
512518 }
513519 return this;
514520 }
521
515522
516523 /**
517524 * Appends part of a string to this string builder.
522529 * @param length the length to append, must be valid
523530 * @return this, to enable chaining
524531 */
525 public StrBuilder append(String str, int startIndex, int length) {
532 public StrBuilder append(final String str, final int startIndex, final int length) {
526533 if (str == null) {
527534 return appendNull();
528535 }
533540 throw new StringIndexOutOfBoundsException("length must be valid");
534541 }
535542 if (length > 0) {
536 int len = length();
543 final int len = length();
537544 ensureCapacity(len + length);
538545 str.getChars(startIndex, startIndex + length, buffer, len);
539546 size += length;
542549 }
543550
544551 /**
552 * Calls {@link String#format(String, Object...)} and appends the result.
553 *
554 * @param format the format string
555 * @param objs the objects to use in the format string
556 * @return {@code this} to enable chaining
557 * @see String#format(String, Object...)
558 * @since 3.2
559 */
560 public StrBuilder append(final String format, final Object... objs) {
561 return append(String.format(format, objs));
562 }
563
564 /**
545565 * Appends a string buffer to this string builder.
546566 * Appending null will call {@link #appendNull()}.
547567 *
548568 * @param str the string buffer to append
549569 * @return this, to enable chaining
550570 */
551 public StrBuilder append(StringBuffer str) {
571 public StrBuilder append(final StringBuffer str) {
552572 if (str == null) {
553573 return appendNull();
554574 }
555 int strLen = str.length();
575 final int strLen = str.length();
556576 if (strLen > 0) {
557 int len = length();
577 final int len = length();
558578 ensureCapacity(len + strLen);
559579 str.getChars(0, strLen, buffer, len);
560580 size += strLen;
571591 * @param length the length to append, must be valid
572592 * @return this, to enable chaining
573593 */
574 public StrBuilder append(StringBuffer str, int startIndex, int length) {
594 public StrBuilder append(final StringBuffer str, final int startIndex, final int length) {
575595 if (str == null) {
576596 return appendNull();
577597 }
582602 throw new StringIndexOutOfBoundsException("length must be valid");
583603 }
584604 if (length > 0) {
585 int len = length();
605 final int len = length();
586606 ensureCapacity(len + length);
587607 str.getChars(startIndex, startIndex + length, buffer, len);
588608 size += length;
591611 }
592612
593613 /**
614 * Appends a StringBuilder to this string builder.
615 * Appending null will call {@link #appendNull()}.
616 *
617 * @param str the StringBuilder to append
618 * @return this, to enable chaining
619 * @since 3.2
620 */
621 public StrBuilder append(final StringBuilder str) {
622 if (str == null) {
623 return appendNull();
624 }
625 final int strLen = str.length();
626 if (strLen > 0) {
627 final int len = length();
628 ensureCapacity(len + strLen);
629 str.getChars(0, strLen, buffer, len);
630 size += strLen;
631 }
632 return this;
633 }
634
635 /**
636 * Appends part of a StringBuilder to this string builder.
637 * Appending null will call {@link #appendNull()}.
638 *
639 * @param str the StringBuilder to append
640 * @param startIndex the start index, inclusive, must be valid
641 * @param length the length to append, must be valid
642 * @return this, to enable chaining
643 * @since 3.2
644 */
645 public StrBuilder append(final StringBuilder str, final int startIndex, final int length) {
646 if (str == null) {
647 return appendNull();
648 }
649 if (startIndex < 0 || startIndex > str.length()) {
650 throw new StringIndexOutOfBoundsException("startIndex must be valid");
651 }
652 if (length < 0 || (startIndex + length) > str.length()) {
653 throw new StringIndexOutOfBoundsException("length must be valid");
654 }
655 if (length > 0) {
656 final int len = length();
657 ensureCapacity(len + length);
658 str.getChars(startIndex, startIndex + length, buffer, len);
659 size += length;
660 }
661 return this;
662 }
663
664 /**
594665 * Appends another string builder to this string builder.
595666 * Appending null will call {@link #appendNull()}.
596667 *
597668 * @param str the string builder to append
598669 * @return this, to enable chaining
599670 */
600 public StrBuilder append(StrBuilder str) {
671 public StrBuilder append(final StrBuilder str) {
601672 if (str == null) {
602673 return appendNull();
603674 }
604 int strLen = str.length();
675 final int strLen = str.length();
605676 if (strLen > 0) {
606 int len = length();
677 final int len = length();
607678 ensureCapacity(len + strLen);
608679 System.arraycopy(str.buffer, 0, buffer, len, strLen);
609680 size += strLen;
620691 * @param length the length to append, must be valid
621692 * @return this, to enable chaining
622693 */
623 public StrBuilder append(StrBuilder str, int startIndex, int length) {
694 public StrBuilder append(final StrBuilder str, final int startIndex, final int length) {
624695 if (str == null) {
625696 return appendNull();
626697 }
631702 throw new StringIndexOutOfBoundsException("length must be valid");
632703 }
633704 if (length > 0) {
634 int len = length();
705 final int len = length();
635706 ensureCapacity(len + length);
636707 str.getChars(startIndex, startIndex + length, buffer, len);
637708 size += length;
646717 * @param chars the char array to append
647718 * @return this, to enable chaining
648719 */
649 public StrBuilder append(char[] chars) {
720 public StrBuilder append(final char[] chars) {
650721 if (chars == null) {
651722 return appendNull();
652723 }
653 int strLen = chars.length;
724 final int strLen = chars.length;
654725 if (strLen > 0) {
655 int len = length();
726 final int len = length();
656727 ensureCapacity(len + strLen);
657728 System.arraycopy(chars, 0, buffer, len, strLen);
658729 size += strLen;
669740 * @param length the length to append, must be valid
670741 * @return this, to enable chaining
671742 */
672 public StrBuilder append(char[] chars, int startIndex, int length) {
743 public StrBuilder append(final char[] chars, final int startIndex, final int length) {
673744 if (chars == null) {
674745 return appendNull();
675746 }
680751 throw new StringIndexOutOfBoundsException("Invalid length: " + length);
681752 }
682753 if (length > 0) {
683 int len = length();
754 final int len = length();
684755 ensureCapacity(len + length);
685756 System.arraycopy(chars, startIndex, buffer, len, length);
686757 size += length;
694765 * @param value the value to append
695766 * @return this, to enable chaining
696767 */
697 public StrBuilder append(boolean value) {
768 public StrBuilder append(final boolean value) {
698769 if (value) {
699770 ensureCapacity(size + 4);
700771 buffer[size++] = 't';
719790 * @return this, to enable chaining
720791 * @since 3.0
721792 */
722 public StrBuilder append(char ch) {
723 int len = length();
793 @Override
794 public StrBuilder append(final char ch) {
795 final int len = length();
724796 ensureCapacity(len + 1);
725797 buffer[size++] = ch;
726798 return this;
732804 * @param value the value to append
733805 * @return this, to enable chaining
734806 */
735 public StrBuilder append(int value) {
807 public StrBuilder append(final int value) {
736808 return append(String.valueOf(value));
737809 }
738810
742814 * @param value the value to append
743815 * @return this, to enable chaining
744816 */
745 public StrBuilder append(long value) {
817 public StrBuilder append(final long value) {
746818 return append(String.valueOf(value));
747819 }
748820
752824 * @param value the value to append
753825 * @return this, to enable chaining
754826 */
755 public StrBuilder append(float value) {
827 public StrBuilder append(final float value) {
756828 return append(String.valueOf(value));
757829 }
758830
762834 * @param value the value to append
763835 * @return this, to enable chaining
764836 */
765 public StrBuilder append(double value) {
837 public StrBuilder append(final double value) {
766838 return append(String.valueOf(value));
767839 }
768840
775847 * @return this, to enable chaining
776848 * @since 2.3
777849 */
778 public StrBuilder appendln(Object obj) {
850 public StrBuilder appendln(final Object obj) {
779851 return append(obj).appendNewLine();
780852 }
781853
787859 * @return this, to enable chaining
788860 * @since 2.3
789861 */
790 public StrBuilder appendln(String str) {
862 public StrBuilder appendln(final String str) {
791863 return append(str).appendNewLine();
792864 }
793865
801873 * @return this, to enable chaining
802874 * @since 2.3
803875 */
804 public StrBuilder appendln(String str, int startIndex, int length) {
876 public StrBuilder appendln(final String str, final int startIndex, final int length) {
805877 return append(str, startIndex, length).appendNewLine();
878 }
879
880 /**
881 * Calls {@link String#format(String, Object...)} and appends the result.
882 *
883 * @param format the format string
884 * @param objs the objects to use in the format string
885 * @return {@code this} to enable chaining
886 * @see String#format(String, Object...)
887 * @since 3.2
888 */
889 public StrBuilder appendln(final String format, final Object... objs) {
890 return append(format, objs).appendNewLine();
806891 }
807892
808893 /**
813898 * @return this, to enable chaining
814899 * @since 2.3
815900 */
816 public StrBuilder appendln(StringBuffer str) {
901 public StrBuilder appendln(final StringBuffer str) {
817902 return append(str).appendNewLine();
903 }
904
905 /**
906 * Appends a string builder followed by a new line to this string builder.
907 * Appending null will call {@link #appendNull()}.
908 *
909 * @param str the string builder to append
910 * @return this, to enable chaining
911 * @since 3.2
912 */
913 public StrBuilder appendln(final StringBuilder str) {
914 return append(str).appendNewLine();
915 }
916
917 /**
918 * Appends part of a string builder followed by a new line to this string builder.
919 * Appending null will call {@link #appendNull()}.
920 *
921 * @param str the string builder to append
922 * @param startIndex the start index, inclusive, must be valid
923 * @param length the length to append, must be valid
924 * @return this, to enable chaining
925 * @since 3.2
926 */
927 public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
928 return append(str, startIndex, length).appendNewLine();
818929 }
819930
820931 /**
827938 * @return this, to enable chaining
828939 * @since 2.3
829940 */
830 public StrBuilder appendln(StringBuffer str, int startIndex, int length) {
941 public StrBuilder appendln(final StringBuffer str, final int startIndex, final int length) {
831942 return append(str, startIndex, length).appendNewLine();
832943 }
833944
839950 * @return this, to enable chaining
840951 * @since 2.3
841952 */
842 public StrBuilder appendln(StrBuilder str) {
953 public StrBuilder appendln(final StrBuilder str) {
843954 return append(str).appendNewLine();
844955 }
845956
853964 * @return this, to enable chaining
854965 * @since 2.3
855966 */
856 public StrBuilder appendln(StrBuilder str, int startIndex, int length) {
967 public StrBuilder appendln(final StrBuilder str, final int startIndex, final int length) {
857968 return append(str, startIndex, length).appendNewLine();
858969 }
859970
865976 * @return this, to enable chaining
866977 * @since 2.3
867978 */
868 public StrBuilder appendln(char[] chars) {
979 public StrBuilder appendln(final char[] chars) {
869980 return append(chars).appendNewLine();
870981 }
871982
879990 * @return this, to enable chaining
880991 * @since 2.3
881992 */
882 public StrBuilder appendln(char[] chars, int startIndex, int length) {
993 public StrBuilder appendln(final char[] chars, final int startIndex, final int length) {
883994 return append(chars, startIndex, length).appendNewLine();
884995 }
885996
8901001 * @return this, to enable chaining
8911002 * @since 2.3
8921003 */
893 public StrBuilder appendln(boolean value) {
1004 public StrBuilder appendln(final boolean value) {
8941005 return append(value).appendNewLine();
8951006 }
8961007
9011012 * @return this, to enable chaining
9021013 * @since 2.3
9031014 */
904 public StrBuilder appendln(char ch) {
1015 public StrBuilder appendln(final char ch) {
9051016 return append(ch).appendNewLine();
9061017 }
9071018
9121023 * @return this, to enable chaining
9131024 * @since 2.3
9141025 */
915 public StrBuilder appendln(int value) {
1026 public StrBuilder appendln(final int value) {
9161027 return append(value).appendNewLine();
9171028 }
9181029
9231034 * @return this, to enable chaining
9241035 * @since 2.3
9251036 */
926 public StrBuilder appendln(long value) {
1037 public StrBuilder appendln(final long value) {
9271038 return append(value).appendNewLine();
9281039 }
9291040
9341045 * @return this, to enable chaining
9351046 * @since 2.3
9361047 */
937 public StrBuilder appendln(float value) {
1048 public StrBuilder appendln(final float value) {
9381049 return append(value).appendNewLine();
9391050 }
9401051
9451056 * @return this, to enable chaining
9461057 * @since 2.3
9471058 */
948 public StrBuilder appendln(double value) {
1059 public StrBuilder appendln(final double value) {
9491060 return append(value).appendNewLine();
9501061 }
9511062
9551066 * Appending a null array will have no effect.
9561067 * Each object is appended using {@link #append(Object)}.
9571068 *
1069 * @param <T> the element type
9581070 * @param array the array to append
9591071 * @return this, to enable chaining
9601072 * @since 2.3
9611073 */
962 public StrBuilder appendAll(Object[] array) {
1074 public <T> StrBuilder appendAll(final T... array) {
9631075 if (array != null && array.length > 0) {
964 for (Object element : array) {
1076 for (final Object element : array) {
9651077 append(element);
9661078 }
9671079 }
9771089 * @return this, to enable chaining
9781090 * @since 2.3
9791091 */
980 public StrBuilder appendAll(Iterable<?> iterable) {
1092 public StrBuilder appendAll(final Iterable<?> iterable) {
9811093 if (iterable != null) {
982 Iterator<?> it = iterable.iterator();
983 while (it.hasNext()) {
984 append(it.next());
1094 for (final Object o : iterable) {
1095 append(o);
9851096 }
9861097 }
9871098 return this;
9961107 * @return this, to enable chaining
9971108 * @since 2.3
9981109 */
999 public StrBuilder appendAll(Iterator<?> it) {
1110 public StrBuilder appendAll(final Iterator<?> it) {
10001111 if (it != null) {
10011112 while (it.hasNext()) {
10021113 append(it.next());
10161127 * @param separator the separator to use, null means no separator
10171128 * @return this, to enable chaining
10181129 */
1019 public StrBuilder appendWithSeparators(Object[] array, String separator) {
1130 public StrBuilder appendWithSeparators(final Object[] array, String separator) {
10201131 if (array != null && array.length > 0) {
10211132 separator = ObjectUtils.toString(separator);
10221133 append(array[0]);
10381149 * @param separator the separator to use, null means no separator
10391150 * @return this, to enable chaining
10401151 */
1041 public StrBuilder appendWithSeparators(Iterable<?> iterable, String separator) {
1152 public StrBuilder appendWithSeparators(final Iterable<?> iterable, String separator) {
10421153 if (iterable != null) {
10431154 separator = ObjectUtils.toString(separator);
1044 Iterator<?> it = iterable.iterator();
1155 final Iterator<?> it = iterable.iterator();
10451156 while (it.hasNext()) {
10461157 append(it.next());
10471158 if (it.hasNext()) {
10621173 * @param separator the separator to use, null means no separator
10631174 * @return this, to enable chaining
10641175 */
1065 public StrBuilder appendWithSeparators(Iterator<?> it, String separator) {
1176 public StrBuilder appendWithSeparators(final Iterator<?> it, String separator) {
10661177 if (it != null) {
10671178 separator = ObjectUtils.toString(separator);
10681179 while (it.hasNext()) {
10961207 * @return this, to enable chaining
10971208 * @since 2.3
10981209 */
1099 public StrBuilder appendSeparator(String separator) {
1210 public StrBuilder appendSeparator(final String separator) {
11001211 return appendSeparator(separator, null);
11011212 }
11021213
11271238 * @return this, to enable chaining
11281239 * @since 2.5
11291240 */
1130 public StrBuilder appendSeparator(String standard, String defaultIfEmpty) {
1131 String str = isEmpty() ? defaultIfEmpty : standard;
1241 public StrBuilder appendSeparator(final String standard, final String defaultIfEmpty) {
1242 final String str = isEmpty() ? defaultIfEmpty : standard;
11321243 if (str != null) {
11331244 append(str);
11341245 }
11541265 * @return this, to enable chaining
11551266 * @since 2.3
11561267 */
1157 public StrBuilder appendSeparator(char separator) {
1268 public StrBuilder appendSeparator(final char separator) {
11581269 if (size() > 0) {
11591270 append(separator);
11601271 }
11721283 * @return this, to enable chaining
11731284 * @since 2.5
11741285 */
1175 public StrBuilder appendSeparator(char standard, char defaultIfEmpty) {
1286 public StrBuilder appendSeparator(final char standard, final char defaultIfEmpty) {
11761287 if (size() > 0) {
11771288 append(standard);
11781289 } else {
12011312 * @return this, to enable chaining
12021313 * @since 2.3
12031314 */
1204 public StrBuilder appendSeparator(String separator, int loopIndex) {
1315 public StrBuilder appendSeparator(final String separator, final int loopIndex) {
12051316 if (separator != null && loopIndex > 0) {
12061317 append(separator);
12071318 }
12281339 * @return this, to enable chaining
12291340 * @since 2.3
12301341 */
1231 public StrBuilder appendSeparator(char separator, int loopIndex) {
1342 public StrBuilder appendSeparator(final char separator, final int loopIndex) {
12321343 if (loopIndex > 0) {
12331344 append(separator);
12341345 }
12431354 * @param padChar the character to append
12441355 * @return this, to enable chaining
12451356 */
1246 public StrBuilder appendPadding(int length, char padChar) {
1357 public StrBuilder appendPadding(final int length, final char padChar) {
12471358 if (length >= 0) {
12481359 ensureCapacity(size + length);
12491360 for (int i = 0; i < length; i++) {
12651376 * @param padChar the pad character to use
12661377 * @return this, to enable chaining
12671378 */
1268 public StrBuilder appendFixedWidthPadLeft(Object obj, int width, char padChar) {
1379 public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) {
12691380 if (width > 0) {
12701381 ensureCapacity(size + width);
12711382 String str = (obj == null ? getNullText() : obj.toString());
12721383 if (str == null) {
12731384 str = "";
12741385 }
1275 int strLen = str.length();
1386 final int strLen = str.length();
12761387 if (strLen >= width) {
12771388 str.getChars(strLen - width, strLen, buffer, size);
12781389 } else {
1279 int padLen = width - strLen;
1390 final int padLen = width - strLen;
12801391 for (int i = 0; i < padLen; i++) {
12811392 buffer[size + i] = padChar;
12821393 }
12971408 * @param padChar the pad character to use
12981409 * @return this, to enable chaining
12991410 */
1300 public StrBuilder appendFixedWidthPadLeft(int value, int width, char padChar) {
1411 public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) {
13011412 return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
13021413 }
13031414
13121423 * @param padChar the pad character to use
13131424 * @return this, to enable chaining
13141425 */
1315 public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
1426 public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) {
13161427 if (width > 0) {
13171428 ensureCapacity(size + width);
13181429 String str = (obj == null ? getNullText() : obj.toString());
13191430 if (str == null) {
13201431 str = "";
13211432 }
1322 int strLen = str.length();
1433 final int strLen = str.length();
13231434 if (strLen >= width) {
13241435 str.getChars(0, width, buffer, size);
13251436 } else {
1326 int padLen = width - strLen;
1437 final int padLen = width - strLen;
13271438 str.getChars(0, strLen, buffer, size);
13281439 for (int i = 0; i < padLen; i++) {
13291440 buffer[size + strLen + i] = padChar;
13441455 * @param padChar the pad character to use
13451456 * @return this, to enable chaining
13461457 */
1347 public StrBuilder appendFixedWidthPadRight(int value, int width, char padChar) {
1458 public StrBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) {
13481459 return appendFixedWidthPadRight(String.valueOf(value), width, padChar);
13491460 }
13501461
13581469 * @return this, to enable chaining
13591470 * @throws IndexOutOfBoundsException if the index is invalid
13601471 */
1361 public StrBuilder insert(int index, Object obj) {
1472 public StrBuilder insert(final int index, final Object obj) {
13621473 if (obj == null) {
13631474 return insert(index, nullText);
13641475 }
13741485 * @return this, to enable chaining
13751486 * @throws IndexOutOfBoundsException if the index is invalid
13761487 */
1377 @SuppressWarnings("null") // str cannot be null
1378 public StrBuilder insert(int index, String str) {
1488 public StrBuilder insert(final int index, String str) {
13791489 validateIndex(index);
13801490 if (str == null) {
13811491 str = nullText;
13821492 }
1383 int strLen = (str == null ? 0 : str.length());
1384 if (strLen > 0) {
1385 int newSize = size + strLen;
1386 ensureCapacity(newSize);
1387 System.arraycopy(buffer, index, buffer, index + strLen, size - index);
1388 size = newSize;
1389 str.getChars(0, strLen, buffer, index); // str cannot be null here
1493 if (str != null) {
1494 final int strLen = str.length();
1495 if (strLen > 0) {
1496 final int newSize = size + strLen;
1497 ensureCapacity(newSize);
1498 System.arraycopy(buffer, index, buffer, index + strLen, size - index);
1499 size = newSize;
1500 str.getChars(0, strLen, buffer, index);
1501 }
13901502 }
13911503 return this;
13921504 }
14001512 * @return this, to enable chaining
14011513 * @throws IndexOutOfBoundsException if the index is invalid
14021514 */
1403 public StrBuilder insert(int index, char chars[]) {
1515 public StrBuilder insert(final int index, final char chars[]) {
14041516 validateIndex(index);
14051517 if (chars == null) {
14061518 return insert(index, nullText);
14071519 }
1408 int len = chars.length;
1520 final int len = chars.length;
14091521 if (len > 0) {
14101522 ensureCapacity(size + len);
14111523 System.arraycopy(buffer, index, buffer, index + len, size - index);
14261538 * @return this, to enable chaining
14271539 * @throws IndexOutOfBoundsException if any index is invalid
14281540 */
1429 public StrBuilder insert(int index, char chars[], int offset, int length) {
1541 public StrBuilder insert(final int index, final char chars[], final int offset, final int length) {
14301542 validateIndex(index);
14311543 if (chars == null) {
14321544 return insert(index, nullText);
14541566 * @return this, to enable chaining
14551567 * @throws IndexOutOfBoundsException if the index is invalid
14561568 */
1457 public StrBuilder insert(int index, boolean value) {
1569 public StrBuilder insert(int index, final boolean value) {
14581570 validateIndex(index);
14591571 if (value) {
14601572 ensureCapacity(size + 4);
14851597 * @return this, to enable chaining
14861598 * @throws IndexOutOfBoundsException if the index is invalid
14871599 */
1488 public StrBuilder insert(int index, char value) {
1600 public StrBuilder insert(final int index, final char value) {
14891601 validateIndex(index);
14901602 ensureCapacity(size + 1);
14911603 System.arraycopy(buffer, index, buffer, index + 1, size - index);
15021614 * @return this, to enable chaining
15031615 * @throws IndexOutOfBoundsException if the index is invalid
15041616 */
1505 public StrBuilder insert(int index, int value) {
1617 public StrBuilder insert(final int index, final int value) {
15061618 return insert(index, String.valueOf(value));
15071619 }
15081620
15141626 * @return this, to enable chaining
15151627 * @throws IndexOutOfBoundsException if the index is invalid
15161628 */
1517 public StrBuilder insert(int index, long value) {
1629 public StrBuilder insert(final int index, final long value) {
15181630 return insert(index, String.valueOf(value));
15191631 }
15201632
15261638 * @return this, to enable chaining
15271639 * @throws IndexOutOfBoundsException if the index is invalid
15281640 */
1529 public StrBuilder insert(int index, float value) {
1641 public StrBuilder insert(final int index, final float value) {
15301642 return insert(index, String.valueOf(value));
15311643 }
15321644
15381650 * @return this, to enable chaining
15391651 * @throws IndexOutOfBoundsException if the index is invalid
15401652 */
1541 public StrBuilder insert(int index, double value) {
1653 public StrBuilder insert(final int index, final double value) {
15421654 return insert(index, String.valueOf(value));
15431655 }
15441656
15511663 * @param len the length, must be valid
15521664 * @throws IndexOutOfBoundsException if any index is invalid
15531665 */
1554 private void deleteImpl(int startIndex, int endIndex, int len) {
1666 private void deleteImpl(final int startIndex, final int endIndex, final int len) {
15551667 System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex);
15561668 size -= len;
15571669 }
15651677 * @return this, to enable chaining
15661678 * @throws IndexOutOfBoundsException if the index is invalid
15671679 */
1568 public StrBuilder delete(int startIndex, int endIndex) {
1680 public StrBuilder delete(final int startIndex, int endIndex) {
15691681 endIndex = validateRange(startIndex, endIndex);
1570 int len = endIndex - startIndex;
1682 final int len = endIndex - startIndex;
15711683 if (len > 0) {
15721684 deleteImpl(startIndex, endIndex, len);
15731685 }
15811693 * @param ch the character to delete
15821694 * @return this, to enable chaining
15831695 */
1584 public StrBuilder deleteAll(char ch) {
1696 public StrBuilder deleteAll(final char ch) {
15851697 for (int i = 0; i < size; i++) {
15861698 if (buffer[i] == ch) {
1587 int start = i;
1699 final int start = i;
15881700 while (++i < size) {
15891701 if (buffer[i] != ch) {
15901702 break;
15911703 }
15921704 }
1593 int len = i - start;
1705 final int len = i - start;
15941706 deleteImpl(start, i, len);
15951707 i -= len;
15961708 }
16041716 * @param ch the character to delete
16051717 * @return this, to enable chaining
16061718 */
1607 public StrBuilder deleteFirst(char ch) {
1719 public StrBuilder deleteFirst(final char ch) {
16081720 for (int i = 0; i < size; i++) {
16091721 if (buffer[i] == ch) {
16101722 deleteImpl(i, i + 1, 1);
16211733 * @param str the string to delete, null causes no action
16221734 * @return this, to enable chaining
16231735 */
1624 public StrBuilder deleteAll(String str) {
1625 int len = (str == null ? 0 : str.length());
1736 public StrBuilder deleteAll(final String str) {
1737 final int len = (str == null ? 0 : str.length());
16261738 if (len > 0) {
16271739 int index = indexOf(str, 0);
16281740 while (index >= 0) {
16391751 * @param str the string to delete, null causes no action
16401752 * @return this, to enable chaining
16411753 */
1642 public StrBuilder deleteFirst(String str) {
1643 int len = (str == null ? 0 : str.length());
1754 public StrBuilder deleteFirst(final String str) {
1755 final int len = (str == null ? 0 : str.length());
16441756 if (len > 0) {
1645 int index = indexOf(str, 0);
1757 final int index = indexOf(str, 0);
16461758 if (index >= 0) {
16471759 deleteImpl(index, index + len, len);
16481760 }
16551767 * Deletes all parts of the builder that the matcher matches.
16561768 * <p>
16571769 * Matchers can be used to perform advanced deletion behaviour.
1658 * For example you could write a matcher to delete all occurances
1770 * For example you could write a matcher to delete all occurrences
16591771 * where the character 'a' is followed by a number.
16601772 *
16611773 * @param matcher the matcher to use to find the deletion, null causes no action
16621774 * @return this, to enable chaining
16631775 */
1664 public StrBuilder deleteAll(StrMatcher matcher) {
1776 public StrBuilder deleteAll(final StrMatcher matcher) {
16651777 return replace(matcher, null, 0, size, -1);
16661778 }
16671779
16751787 * @param matcher the matcher to use to find the deletion, null causes no action
16761788 * @return this, to enable chaining
16771789 */
1678 public StrBuilder deleteFirst(StrMatcher matcher) {
1790 public StrBuilder deleteFirst(final StrMatcher matcher) {
16791791 return replace(matcher, null, 0, size, 1);
16801792 }
16811793
16901802 * @param insertLen the length of the insert string, must be valid
16911803 * @throws IndexOutOfBoundsException if any index is invalid
16921804 */
1693 private void replaceImpl(int startIndex, int endIndex, int removeLen, String insertStr, int insertLen) {
1694 int newSize = size - removeLen + insertLen;
1805 private void replaceImpl(final int startIndex, final int endIndex, final int removeLen, final String insertStr, final int insertLen) {
1806 final int newSize = size - removeLen + insertLen;
16951807 if (insertLen != removeLen) {
16961808 ensureCapacity(newSize);
16971809 System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex);
17131825 * @return this, to enable chaining
17141826 * @throws IndexOutOfBoundsException if the index is invalid
17151827 */
1716 public StrBuilder replace(int startIndex, int endIndex, String replaceStr) {
1828 public StrBuilder replace(final int startIndex, int endIndex, final String replaceStr) {
17171829 endIndex = validateRange(startIndex, endIndex);
1718 int insertLen = (replaceStr == null ? 0 : replaceStr.length());
1830 final int insertLen = (replaceStr == null ? 0 : replaceStr.length());
17191831 replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen);
17201832 return this;
17211833 }
17291841 * @param replace the replace character
17301842 * @return this, to enable chaining
17311843 */
1732 public StrBuilder replaceAll(char search, char replace) {
1844 public StrBuilder replaceAll(final char search, final char replace) {
17331845 if (search != replace) {
17341846 for (int i = 0; i < size; i++) {
17351847 if (buffer[i] == search) {
17481860 * @param replace the replace character
17491861 * @return this, to enable chaining
17501862 */
1751 public StrBuilder replaceFirst(char search, char replace) {
1863 public StrBuilder replaceFirst(final char search, final char replace) {
17521864 if (search != replace) {
17531865 for (int i = 0; i < size; i++) {
17541866 if (buffer[i] == search) {
17681880 * @param replaceStr the replace string, null is equivalent to an empty string
17691881 * @return this, to enable chaining
17701882 */
1771 public StrBuilder replaceAll(String searchStr, String replaceStr) {
1772 int searchLen = (searchStr == null ? 0 : searchStr.length());
1883 public StrBuilder replaceAll(final String searchStr, final String replaceStr) {
1884 final int searchLen = (searchStr == null ? 0 : searchStr.length());
17731885 if (searchLen > 0) {
1774 int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
1886 final int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
17751887 int index = indexOf(searchStr, 0);
17761888 while (index >= 0) {
17771889 replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
17881900 * @param replaceStr the replace string, null is equivalent to an empty string
17891901 * @return this, to enable chaining
17901902 */
1791 public StrBuilder replaceFirst(String searchStr, String replaceStr) {
1792 int searchLen = (searchStr == null ? 0 : searchStr.length());
1903 public StrBuilder replaceFirst(final String searchStr, final String replaceStr) {
1904 final int searchLen = (searchStr == null ? 0 : searchStr.length());
17931905 if (searchLen > 0) {
1794 int index = indexOf(searchStr, 0);
1906 final int index = indexOf(searchStr, 0);
17951907 if (index >= 0) {
1796 int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
1908 final int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
17971909 replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
17981910 }
17991911 }
18051917 * Replaces all matches within the builder with the replace string.
18061918 * <p>
18071919 * Matchers can be used to perform advanced replace behaviour.
1808 * For example you could write a matcher to replace all occurances
1920 * For example you could write a matcher to replace all occurrences
18091921 * where the character 'a' is followed by a number.
18101922 *
18111923 * @param matcher the matcher to use to find the deletion, null causes no action
18121924 * @param replaceStr the replace string, null is equivalent to an empty string
18131925 * @return this, to enable chaining
18141926 */
1815 public StrBuilder replaceAll(StrMatcher matcher, String replaceStr) {
1927 public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) {
18161928 return replace(matcher, replaceStr, 0, size, -1);
18171929 }
18181930
18271939 * @param replaceStr the replace string, null is equivalent to an empty string
18281940 * @return this, to enable chaining
18291941 */
1830 public StrBuilder replaceFirst(StrMatcher matcher, String replaceStr) {
1942 public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr) {
18311943 return replace(matcher, replaceStr, 0, size, 1);
18321944 }
18331945
18361948 * Advanced search and replaces within the builder using a matcher.
18371949 * <p>
18381950 * Matchers can be used to perform advanced behaviour.
1839 * For example you could write a matcher to delete all occurances
1951 * For example you could write a matcher to delete all occurrences
18401952 * where the character 'a' is followed by a number.
18411953 *
18421954 * @param matcher the matcher to use to find the deletion, null causes no action
18491961 * @throws IndexOutOfBoundsException if start index is invalid
18501962 */
18511963 public StrBuilder replace(
1852 StrMatcher matcher, String replaceStr,
1853 int startIndex, int endIndex, int replaceCount) {
1964 final StrMatcher matcher, final String replaceStr,
1965 final int startIndex, int endIndex, final int replaceCount) {
18541966 endIndex = validateRange(startIndex, endIndex);
18551967 return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount);
18561968 }
18591971 * Replaces within the builder using a matcher.
18601972 * <p>
18611973 * Matchers can be used to perform advanced behaviour.
1862 * For example you could write a matcher to delete all occurances
1974 * For example you could write a matcher to delete all occurrences
18631975 * where the character 'a' is followed by a number.
18641976 *
18651977 * @param matcher the matcher to use to find the deletion, null causes no action
18711983 * @throws IndexOutOfBoundsException if any index is invalid
18721984 */
18731985 private StrBuilder replaceImpl(
1874 StrMatcher matcher, String replaceStr,
1875 int from, int to, int replaceCount) {
1986 final StrMatcher matcher, final String replaceStr,
1987 final int from, int to, int replaceCount) {
18761988 if (matcher == null || size == 0) {
18771989 return this;
18781990 }
1879 int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
1880 char[] buf = buffer;
1991 final int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
1992 final char[] buf = buffer;
18811993 for (int i = from; i < to && replaceCount != 0; i++) {
1882 int removeLen = matcher.isMatch(buf, i, from, to);
1994 final int removeLen = matcher.isMatch(buf, i, from, to);
18831995 if (removeLen > 0) {
18841996 replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen);
18851997 to = to - removeLen + replaceLen;
19032015 return this;
19042016 }
19052017
1906 int half = size / 2;
1907 char[] buf = buffer;
2018 final int half = size / 2;
2019 final char[] buf = buffer;
19082020 for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++,rightIdx--) {
1909 char swap = buf[leftIdx];
2021 final char swap = buf[leftIdx];
19102022 buf[leftIdx] = buf[rightIdx];
19112023 buf[rightIdx] = swap;
19122024 }
19252037 return this;
19262038 }
19272039 int len = size;
1928 char[] buf = buffer;
2040 final char[] buf = buffer;
19292041 int pos = 0;
19302042 while (pos < len && buf[pos] <= ' ') {
19312043 pos++;
19512063 * @param str the string to search for, null returns false
19522064 * @return true if the builder starts with the string
19532065 */
1954 public boolean startsWith(String str) {
2066 public boolean startsWith(final String str) {
19552067 if (str == null) {
19562068 return false;
19572069 }
1958 int len = str.length();
2070 final int len = str.length();
19592071 if (len == 0) {
19602072 return true;
19612073 }
19782090 * @param str the string to search for, null returns false
19792091 * @return true if the builder ends with the string
19802092 */
1981 public boolean endsWith(String str) {
2093 public boolean endsWith(final String str) {
19822094 if (str == null) {
19832095 return false;
19842096 }
1985 int len = str.length();
2097 final int len = str.length();
19862098 if (len == 0) {
19872099 return true;
19882100 }
20032115 * {@inheritDoc}
20042116 * @since 3.0
20052117 */
2006 public CharSequence subSequence(int startIndex, int endIndex) {
2118 @Override
2119 public CharSequence subSequence(final int startIndex, final int endIndex) {
20072120 if (startIndex < 0) {
20082121 throw new StringIndexOutOfBoundsException(startIndex);
20092122 }
20232136 * @return the new string
20242137 * @throws IndexOutOfBoundsException if the index is invalid
20252138 */
2026 public String substring(int start) {
2139 public String substring(final int start) {
20272140 return substring(start, size);
20282141 }
20292142
20402153 * @return the new string
20412154 * @throws IndexOutOfBoundsException if the index is invalid
20422155 */
2043 public String substring(int startIndex, int endIndex) {
2156 public String substring(final int startIndex, int endIndex) {
20442157 endIndex = validateRange(startIndex, endIndex);
20452158 return new String(buffer, startIndex, endIndex - startIndex);
20462159 }
20572170 * @param length the number of characters to extract, negative returns empty string
20582171 * @return the new string
20592172 */
2060 public String leftString(int length) {
2173 public String leftString(final int length) {
20612174 if (length <= 0) {
20622175 return "";
20632176 } else if (length >= size) {
20792192 * @param length the number of characters to extract, negative returns empty string
20802193 * @return the new string
20812194 */
2082 public String rightString(int length) {
2195 public String rightString(final int length) {
20832196 if (length <= 0) {
20842197 return "";
20852198 } else if (length >= size) {
21052218 * @param length the number of characters to extract, negative returns empty string
21062219 * @return the new string
21072220 */
2108 public String midString(int index, int length) {
2221 public String midString(int index, final int length) {
21092222 if (index < 0) {
21102223 index = 0;
21112224 }
21142227 }
21152228 if (size <= index + length) {
21162229 return new String(buffer, index, size - index);
2117 } else {
2118 return new String(buffer, index, length);
2119 }
2230 }
2231 return new String(buffer, index, length);
21202232 }
21212233
21222234 //-----------------------------------------------------------------------
21262238 * @param ch the character to find
21272239 * @return true if the builder contains the character
21282240 */
2129 public boolean contains(char ch) {
2130 char[] thisBuf = buffer;
2241 public boolean contains(final char ch) {
2242 final char[] thisBuf = buffer;
21312243 for (int i = 0; i < this.size; i++) {
21322244 if (thisBuf[i] == ch) {
21332245 return true;
21422254 * @param str the string to find
21432255 * @return true if the builder contains the string
21442256 */
2145 public boolean contains(String str) {
2257 public boolean contains(final String str) {
21462258 return indexOf(str, 0) >= 0;
21472259 }
21482260
21572269 * @param matcher the matcher to use, null returns -1
21582270 * @return true if the matcher finds a match in the builder
21592271 */
2160 public boolean contains(StrMatcher matcher) {
2272 public boolean contains(final StrMatcher matcher) {
21612273 return indexOf(matcher, 0) >= 0;
21622274 }
21632275
21682280 * @param ch the character to find
21692281 * @return the first index of the character, or -1 if not found
21702282 */
2171 public int indexOf(char ch) {
2283 public int indexOf(final char ch) {
21722284 return indexOf(ch, 0);
21732285 }
21742286
21792291 * @param startIndex the index to start at, invalid index rounded to edge
21802292 * @return the first index of the character, or -1 if not found
21812293 */
2182 public int indexOf(char ch, int startIndex) {
2294 public int indexOf(final char ch, int startIndex) {
21832295 startIndex = (startIndex < 0 ? 0 : startIndex);
21842296 if (startIndex >= size) {
21852297 return -1;
21862298 }
2187 char[] thisBuf = buffer;
2299 final char[] thisBuf = buffer;
21882300 for (int i = startIndex; i < size; i++) {
21892301 if (thisBuf[i] == ch) {
21902302 return i;
22012313 * @param str the string to find, null returns -1
22022314 * @return the first index of the string, or -1 if not found
22032315 */
2204 public int indexOf(String str) {
2316 public int indexOf(final String str) {
22052317 return indexOf(str, 0);
22062318 }
22072319
22152327 * @param startIndex the index to start at, invalid index rounded to edge
22162328 * @return the first index of the string, or -1 if not found
22172329 */
2218 public int indexOf(String str, int startIndex) {
2330 public int indexOf(final String str, int startIndex) {
22192331 startIndex = (startIndex < 0 ? 0 : startIndex);
22202332 if (str == null || startIndex >= size) {
22212333 return -1;
22222334 }
2223 int strLen = str.length();
2335 final int strLen = str.length();
22242336 if (strLen == 1) {
22252337 return indexOf(str.charAt(0), startIndex);
22262338 }
22302342 if (strLen > size) {
22312343 return -1;
22322344 }
2233 char[] thisBuf = buffer;
2234 int len = size - strLen + 1;
2345 final char[] thisBuf = buffer;
2346 final int len = size - strLen + 1;
22352347 outer:
22362348 for (int i = startIndex; i < len; i++) {
22372349 for (int j = 0; j < strLen; j++) {
22542366 * @param matcher the matcher to use, null returns -1
22552367 * @return the first index matched, or -1 if not found
22562368 */
2257 public int indexOf(StrMatcher matcher) {
2369 public int indexOf(final StrMatcher matcher) {
22582370 return indexOf(matcher, 0);
22592371 }
22602372
22702382 * @param startIndex the index to start at, invalid index rounded to edge
22712383 * @return the first index matched, or -1 if not found
22722384 */
2273 public int indexOf(StrMatcher matcher, int startIndex) {
2385 public int indexOf(final StrMatcher matcher, int startIndex) {
22742386 startIndex = (startIndex < 0 ? 0 : startIndex);
22752387 if (matcher == null || startIndex >= size) {
22762388 return -1;
22772389 }
2278 int len = size;
2279 char[] buf = buffer;
2390 final int len = size;
2391 final char[] buf = buffer;
22802392 for (int i = startIndex; i < len; i++) {
22812393 if (matcher.isMatch(buf, i, startIndex, len) > 0) {
22822394 return i;
22922404 * @param ch the character to find
22932405 * @return the last index of the character, or -1 if not found
22942406 */
2295 public int lastIndexOf(char ch) {
2407 public int lastIndexOf(final char ch) {
22962408 return lastIndexOf(ch, size - 1);
22972409 }
22982410
23032415 * @param startIndex the index to start at, invalid index rounded to edge
23042416 * @return the last index of the character, or -1 if not found
23052417 */
2306 public int lastIndexOf(char ch, int startIndex) {
2418 public int lastIndexOf(final char ch, int startIndex) {
23072419 startIndex = (startIndex >= size ? size - 1 : startIndex);
23082420 if (startIndex < 0) {
23092421 return -1;
23242436 * @param str the string to find, null returns -1
23252437 * @return the last index of the string, or -1 if not found
23262438 */
2327 public int lastIndexOf(String str) {
2439 public int lastIndexOf(final String str) {
23282440 return lastIndexOf(str, size - 1);
23292441 }
23302442
23382450 * @param startIndex the index to start at, invalid index rounded to edge
23392451 * @return the last index of the string, or -1 if not found
23402452 */
2341 public int lastIndexOf(String str, int startIndex) {
2453 public int lastIndexOf(final String str, int startIndex) {
23422454 startIndex = (startIndex >= size ? size - 1 : startIndex);
23432455 if (str == null || startIndex < 0) {
23442456 return -1;
23452457 }
2346 int strLen = str.length();
2458 final int strLen = str.length();
23472459 if (strLen > 0 && strLen <= size) {
23482460 if (strLen == 1) {
23492461 return lastIndexOf(str.charAt(0), startIndex);
23752487 * @param matcher the matcher to use, null returns -1
23762488 * @return the last index matched, or -1 if not found
23772489 */
2378 public int lastIndexOf(StrMatcher matcher) {
2490 public int lastIndexOf(final StrMatcher matcher) {
23792491 return lastIndexOf(matcher, size);
23802492 }
23812493
23912503 * @param startIndex the index to start at, invalid index rounded to edge
23922504 * @return the last index matched, or -1 if not found
23932505 */
2394 public int lastIndexOf(StrMatcher matcher, int startIndex) {
2506 public int lastIndexOf(final StrMatcher matcher, int startIndex) {
23952507 startIndex = (startIndex >= size ? size - 1 : startIndex);
23962508 if (matcher == null || startIndex < 0) {
23972509 return -1;
23982510 }
2399 char[] buf = buffer;
2400 int endIndex = startIndex + 1;
2511 final char[] buf = buffer;
2512 final int endIndex = startIndex + 1;
24012513 for (int i = startIndex; i >= 0; i--) {
24022514 if (matcher.isMatch(buf, i, 0, endIndex) > 0) {
24032515 return i;
25302642 * @param other the object to check, null returns false
25312643 * @return true if the builders contain the same characters in the same order
25322644 */
2533 public boolean equalsIgnoreCase(StrBuilder other) {
2645 public boolean equalsIgnoreCase(final StrBuilder other) {
25342646 if (this == other) {
25352647 return true;
25362648 }
25372649 if (this.size != other.size) {
25382650 return false;
25392651 }
2540 char thisBuf[] = this.buffer;
2541 char otherBuf[] = other.buffer;
2652 final char thisBuf[] = this.buffer;
2653 final char otherBuf[] = other.buffer;
25422654 for (int i = size - 1; i >= 0; i--) {
2543 char c1 = thisBuf[i];
2544 char c2 = otherBuf[i];
2655 final char c1 = thisBuf[i];
2656 final char c2 = otherBuf[i];
25452657 if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) {
25462658 return false;
25472659 }
25562668 * @param other the object to check, null returns false
25572669 * @return true if the builders contain the same characters in the same order
25582670 */
2559 public boolean equals(StrBuilder other) {
2671 public boolean equals(final StrBuilder other) {
25602672 if (this == other) {
25612673 return true;
25622674 }
25632675 if (this.size != other.size) {
25642676 return false;
25652677 }
2566 char thisBuf[] = this.buffer;
2567 char otherBuf[] = other.buffer;
2678 final char thisBuf[] = this.buffer;
2679 final char otherBuf[] = other.buffer;
25682680 for (int i = size - 1; i >= 0; i--) {
25692681 if (thisBuf[i] != otherBuf[i]) {
25702682 return false;
25812693 * @return true if the builders contain the same characters in the same order
25822694 */
25832695 @Override
2584 public boolean equals(Object obj) {
2696 public boolean equals(final Object obj) {
25852697 if (obj instanceof StrBuilder) {
25862698 return equals((StrBuilder) obj);
25872699 }
25952707 */
25962708 @Override
25972709 public int hashCode() {
2598 char buf[] = buffer;
2710 final char buf[] = buffer;
25992711 int hash = 0;
26002712 for (int i = size - 1; i >= 0; i--) {
26012713 hash = 31 * hash + buf[i];
26262738 */
26272739 public StringBuffer toStringBuffer() {
26282740 return new StringBuffer(size).append(buffer, 0, size);
2741 }
2742
2743 /**
2744 * Gets a StringBuilder version of the string builder, creating a
2745 * new instance each time the method is called.
2746 *
2747 * @return the builder as a StringBuilder
2748 * @since 3.2
2749 */
2750 public StringBuilder toStringBuilder() {
2751 return new StringBuilder(size).append(buffer, 0, size);
2752 }
2753
2754 /**
2755 * Implement the {@link Builder} interface.
2756 * @return the builder as a String
2757 * @since 3.2
2758 * @see #toString()
2759 */
2760 @Override
2761 public String build() {
2762 return toString();
26292763 }
26302764
26312765 //-----------------------------------------------------------------------
26382772 * @return the new string
26392773 * @throws IndexOutOfBoundsException if the index is invalid
26402774 */
2641 protected int validateRange(int startIndex, int endIndex) {
2775 protected int validateRange(final int startIndex, int endIndex) {
26422776 if (startIndex < 0) {
26432777 throw new StringIndexOutOfBoundsException(startIndex);
26442778 }
26572791 * @param index the index, must be valid
26582792 * @throws IndexOutOfBoundsException if the index is invalid
26592793 */
2660 protected void validateIndex(int index) {
2794 protected void validateIndex(final int index) {
26612795 if (index < 0 || index > size) {
26622796 throw new StringIndexOutOfBoundsException(index);
26632797 }
26782812
26792813 /** {@inheritDoc} */
26802814 @Override
2681 protected List<String> tokenize(char[] chars, int offset, int count) {
2815 protected List<String> tokenize(final char[] chars, final int offset, final int count) {
26822816 if (chars == null) {
26832817 return super.tokenize(StrBuilder.this.buffer, 0, StrBuilder.this.size());
2684 } else {
2685 return super.tokenize(chars, offset, count);
2686 }
2818 }
2819 return super.tokenize(chars, offset, count);
26872820 }
26882821
26892822 /** {@inheritDoc} */
26902823 @Override
26912824 public String getContent() {
2692 String str = super.getContent();
2825 final String str = super.getContent();
26932826 if (str == null) {
26942827 return StrBuilder.this.toString();
2695 } else {
2696 return str;
2697 }
2698 }
2699 }
2700
2701 //-----------------------------------------------------------------------
2702 /**
2703 * Inner class to allow StrBuilder to operate as a writer.
2828 }
2829 return str;
2830 }
2831 }
2832
2833 //-----------------------------------------------------------------------
2834 /**
2835 * Inner class to allow StrBuilder to operate as a reader.
27042836 */
27052837 class StrBuilderReader extends Reader {
27062838 /** The current stream position. */
27322864
27332865 /** {@inheritDoc} */
27342866 @Override
2735 public int read(char b[], int off, int len) {
2867 public int read(final char b[], final int off, int len) {
27362868 if (off < 0 || len < 0 || off > b.length ||
27372869 (off + len) > b.length || (off + len) < 0) {
27382870 throw new IndexOutOfBoundsException();
27782910
27792911 /** {@inheritDoc} */
27802912 @Override
2781 public void mark(int readAheadLimit) {
2913 public void mark(final int readAheadLimit) {
27822914 mark = pos;
27832915 }
27842916
28162948
28172949 /** {@inheritDoc} */
28182950 @Override
2819 public void write(int c) {
2951 public void write(final int c) {
28202952 StrBuilder.this.append((char) c);
28212953 }
28222954
28232955 /** {@inheritDoc} */
28242956 @Override
2825 public void write(char[] cbuf) {
2957 public void write(final char[] cbuf) {
28262958 StrBuilder.this.append(cbuf);
28272959 }
28282960
28292961 /** {@inheritDoc} */
28302962 @Override
2831 public void write(char[] cbuf, int off, int len) {
2963 public void write(final char[] cbuf, final int off, final int len) {
28322964 StrBuilder.this.append(cbuf, off, len);
28332965 }
28342966
28352967 /** {@inheritDoc} */
28362968 @Override
2837 public void write(String str) {
2969 public void write(final String str) {
28382970 StrBuilder.this.append(str);
28392971 }
28402972
28412973 /** {@inheritDoc} */
28422974 @Override
2843 public void write(String str, int off, int len) {
2975 public void write(final String str, final int off, final int len) {
28442976 StrBuilder.this.append(str, off, len);
28452977 }
28462978 }
3131 * key as a primary key, and looked up the value on demand from the database
3232 *
3333 * @since 2.2
34 * @version $Id: StrLookup.java 1153484 2011-08-03 13:39:42Z ggregory $
34 * @version $Id: StrLookup.java 1436770 2013-01-22 07:09:45Z ggregory $
3535 */
3636 public abstract class StrLookup<V> {
3737
5151 @SuppressWarnings("unchecked") // System property keys and values are always Strings
5252 final Map<String, String> properties = (Map<String, String>) propMap;
5353 lookup = new MapStrLookup<String>(properties);
54 } catch (SecurityException ex) {
54 } catch (final SecurityException ex) {
5555 lookup = NONE_LOOKUP;
5656 }
5757 SYSTEM_PROPERTIES_LOOKUP = lookup;
9292 * @param map the map of keys to values, may be null
9393 * @return a lookup using the map, not null
9494 */
95 public static <V> StrLookup<V> mapLookup(Map<String, V> map) {
95 public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
9696 return new MapStrLookup<V>(map);
9797 }
9898
143143 *
144144 * @param map the map of keys to values, may be null
145145 */
146 MapStrLookup(Map<String, V> map) {
146 MapStrLookup(final Map<String, V> map) {
147147 this.map = map;
148148 }
149149
157157 * @return the matching value, null if no match
158158 */
159159 @Override
160 public String lookup(String key) {
160 public String lookup(final String key) {
161161 if (map == null) {
162162 return null;
163163 }
164 Object obj = map.get(key);
164 final Object obj = map.get(key);
165165 if (obj == null) {
166166 return null;
167167 }
2727 * If these do not suffice, you can subclass and implement your own matcher.
2828 *
2929 * @since 2.2
30 * @version $Id: StrMatcher.java 1144925 2011-07-10 18:07:05Z ggregory $
30 * @version $Id: StrMatcher.java 1436770 2013-01-22 07:09:45Z ggregory $
3131 */
3232 public abstract class StrMatcher {
3333
159159 * @param ch the character to match, must not be null
160160 * @return a new Matcher for the given char
161161 */
162 public static StrMatcher charMatcher(char ch) {
162 public static StrMatcher charMatcher(final char ch) {
163163 return new CharMatcher(ch);
164164 }
165165
169169 * @param chars the characters to match, null or empty matches nothing
170170 * @return a new matcher for the given char[]
171171 */
172 public static StrMatcher charSetMatcher(char... chars) {
172 public static StrMatcher charSetMatcher(final char... chars) {
173173 if (chars == null || chars.length == 0) {
174174 return NONE_MATCHER;
175175 }
185185 * @param chars the characters to match, null or empty matches nothing
186186 * @return a new Matcher for the given characters
187187 */
188 public static StrMatcher charSetMatcher(String chars) {
189 if (chars == null || chars.length() == 0) {
188 public static StrMatcher charSetMatcher(final String chars) {
189 if (StringUtils.isEmpty(chars)) {
190190 return NONE_MATCHER;
191191 }
192192 if (chars.length() == 1) {
201201 * @param str the string to match, null or empty matches nothing
202202 * @return a new Matcher for the given String
203203 */
204 public static StrMatcher stringMatcher(String str) {
204 public static StrMatcher stringMatcher(final String str) {
205205 if (StringUtils.isEmpty(str)) {
206206 return NONE_MATCHER;
207207 }
229229 * Only values in the buffer between the specifed indices may be accessed.
230230 * <p>
231231 * The matching code may check one character or many.
232 * It may check characters preceeding <code>pos</code> as well as those
232 * It may check characters preceding <code>pos</code> as well as those
233233 * after, so long as no checks exceed the bounds specified.
234234 * <p>
235235 * It must return zero for no match, or a positive number if a match was found.
253253 * The API guarantees that <code>pos</code> is a valid index for <code>buffer</code>.
254254 * <p>
255255 * The matching code may check one character or many.
256 * It may check characters preceeding <code>pos</code> as well as those after.
256 * It may check characters preceding <code>pos</code> as well as those after.
257257 * <p>
258258 * It must return zero for no match, or a positive number if a match was found.
259259 * The number indicates the number of characters that matched.
263263 * @return the number of matching characters, zero for no match
264264 * @since 2.4
265265 */
266 public int isMatch(char[] buffer, int pos) {
266 public int isMatch(final char[] buffer, final int pos) {
267267 return isMatch(buffer, pos, 0, buffer.length);
268268 }
269269
280280 *
281281 * @param chars the characters to match, must not be null
282282 */
283 CharSetMatcher(char chars[]) {
283 CharSetMatcher(final char chars[]) {
284284 super();
285285 this.chars = chars.clone();
286286 Arrays.sort(this.chars);
296296 * @return the number of matching characters, zero for no match
297297 */
298298 @Override
299 public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
299 public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
300300 return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0;
301301 }
302302 }
314314 *
315315 * @param ch the character to match
316316 */
317 CharMatcher(char ch) {
317 CharMatcher(final char ch) {
318318 super();
319319 this.ch = ch;
320320 }
329329 * @return the number of matching characters, zero for no match
330330 */
331331 @Override
332 public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
332 public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
333333 return ch == buffer[pos] ? 1 : 0;
334334 }
335335 }
347347 *
348348 * @param str the string to match, must not be null
349349 */
350 StringMatcher(String str) {
350 StringMatcher(final String str) {
351351 super();
352352 chars = str.toCharArray();
353353 }
362362 * @return the number of matching characters, zero for no match
363363 */
364364 @Override
365 public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
366 int len = chars.length;
365 public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
366 final int len = chars.length;
367367 if (pos + len > bufferEnd) {
368368 return 0;
369369 }
399399 * @return the number of matching characters, zero for no match
400400 */
401401 @Override
402 public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
402 public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
403403 return 0;
404404 }
405405 }
427427 * @return the number of matching characters, zero for no match
428428 */
429429 @Override
430 public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
430 public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
431431 return buffer[pos] <= 32 ? 1 : 0;
432432 }
433433 }
2121 import java.util.List;
2222 import java.util.Map;
2323 import java.util.Properties;
24
25 import org.apache.commons.lang3.StringUtils;
2426
2527 /**
2628 * Substitutes variables within a string by values.
5658 * yielding:
5759 * <pre>
5860 * The quick brown fox jumped over the lazy dog.
61 * </pre>
62 * <p>
63 * Also, this class allows to set a default value for unresolved variables.
64 * The default value for a variable can be appended to the variable name after the variable
65 * default value delimiter. The default value of the variable default value delimiter is ':-',
66 * as in bash and other *nix shells, as those are arguably where the default ${} delimiter set originated.
67 * The variable default value delimiter can be manually set by calling {@link #setValueDelimiterMatcher(StrMatcher)},
68 * {@link #setValueDelimiter(char)} or {@link #setValueDelimiter(String)}.
69 * The following shows an example with varialbe default value settings:
70 * <pre>
71 * Map valuesMap = HashMap();
72 * valuesMap.put(&quot;animal&quot;, &quot;quick brown fox&quot;);
73 * valuesMap.put(&quot;target&quot;, &quot;lazy dog&quot;);
74 * String templateString = &quot;The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}.&quot;;
75 * StrSubstitutor sub = new StrSubstitutor(valuesMap);
76 * String resolvedString = sub.replace(templateString);
77 * </pre>
78 * yielding:
79 * <pre>
80 * The quick brown fox jumped over the lazy dog. 1234567890.
5981 * </pre>
6082 * <p>
6183 * In addition to this usage pattern there are some static convenience methods that
96118 * {@link #setEnableSubstitutionInVariables(boolean) enableSubstitutionInVariables}
97119 * property to <b>true</b>.
98120 *
99 * @version $Id: StrSubstitutor.java 1199894 2011-11-09 17:53:59Z ggregory $
121 * @version $Id: StrSubstitutor.java 1552654 2013-12-20 13:25:37Z britter $
100122 * @since 2.2
101123 */
102124 public class StrSubstitutor {
113135 * Constant for the default variable suffix.
114136 */
115137 public static final StrMatcher DEFAULT_SUFFIX = StrMatcher.stringMatcher("}");
138 /**
139 * Constant for the default value delimiter of a variable.
140 * @since 3.2
141 */
142 public static final StrMatcher DEFAULT_VALUE_DELIMITER = StrMatcher.stringMatcher(":-");
116143
117144 /**
118145 * Stores the escape character.
126153 * Stores the variable suffix.
127154 */
128155 private StrMatcher suffixMatcher;
156 /**
157 * Stores the default variable value delimiter
158 */
159 private StrMatcher valueDelimiterMatcher;
129160 /**
130161 * Variable resolution is delegated to an implementor of VariableResolver.
131162 */
145176 * @param valueMap the map with the values, may be null
146177 * @return the result of the replace operation
147178 */
148 public static <V> String replace(Object source, Map<String, V> valueMap) {
179 public static <V> String replace(final Object source, final Map<String, V> valueMap) {
149180 return new StrSubstitutor(valueMap).replace(source);
150181 }
151182
162193 * @return the result of the replace operation
163194 * @throws IllegalArgumentException if the prefix or suffix is null
164195 */
165 public static <V> String replace(Object source, Map<String, V> valueMap, String prefix, String suffix) {
196 public static <V> String replace(final Object source, final Map<String, V> valueMap, final String prefix, final String suffix) {
166197 return new StrSubstitutor(valueMap, prefix, suffix).replace(source);
167198 }
168199
174205 * @param valueProperties the properties with values, may be null
175206 * @return the result of the replace operation
176207 */
177 public static String replace(Object source, Properties valueProperties) {
208 public static String replace(final Object source, final Properties valueProperties) {
178209 if (valueProperties == null) {
179210 return source.toString();
180211 }
181 Map<String,String> valueMap = new HashMap<String,String>();
182 Enumeration<?> propNames = valueProperties.propertyNames();
212 final Map<String,String> valueMap = new HashMap<String,String>();
213 final Enumeration<?> propNames = valueProperties.propertyNames();
183214 while (propNames.hasMoreElements()) {
184 String propName = (String)propNames.nextElement();
185 String propValue = valueProperties.getProperty(propName);
215 final String propName = (String)propNames.nextElement();
216 final String propValue = valueProperties.getProperty(propName);
186217 valueMap.put(propName, propValue);
187218 }
188219 return StrSubstitutor.replace(source, valueMap);
195226 * @param source the source text containing the variables to substitute, null returns null
196227 * @return the result of the replace operation
197228 */
198 public static String replaceSystemProperties(Object source) {
229 public static String replaceSystemProperties(final Object source) {
199230 return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source);
200231 }
201232
215246 * @param <V> the type of the values in the map
216247 * @param valueMap the map with the variables' values, may be null
217248 */
218 public <V> StrSubstitutor(Map<String, V> valueMap) {
249 public <V> StrSubstitutor(final Map<String, V> valueMap) {
219250 this(StrLookup.mapLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
220251 }
221252
228259 * @param suffix the suffix for variables, not null
229260 * @throws IllegalArgumentException if the prefix or suffix is null
230261 */
231 public <V> StrSubstitutor(Map<String, V> valueMap, String prefix, String suffix) {
262 public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix) {
232263 this(StrLookup.mapLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE);
233264 }
234265
242273 * @param escape the escape character
243274 * @throws IllegalArgumentException if the prefix or suffix is null
244275 */
245 public <V> StrSubstitutor(Map<String, V> valueMap, String prefix, String suffix, char escape) {
276 public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
277 final char escape) {
246278 this(StrLookup.mapLookup(valueMap), prefix, suffix, escape);
247279 }
248280
249281 /**
250282 * Creates a new instance and initializes it.
251283 *
284 * @param <V> the type of the values in the map
285 * @param valueMap the map with the variables' values, may be null
286 * @param prefix the prefix for variables, not null
287 * @param suffix the suffix for variables, not null
288 * @param escape the escape character
289 * @param valueDelimiter the variable default value delimiter, may be null
290 * @throws IllegalArgumentException if the prefix or suffix is null
291 * @since 3.2
292 */
293 public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
294 final char escape, final String valueDelimiter) {
295 this(StrLookup.mapLookup(valueMap), prefix, suffix, escape, valueDelimiter);
296 }
297
298 /**
299 * Creates a new instance and initializes it.
300 *
252301 * @param variableResolver the variable resolver, may be null
253302 */
254 public StrSubstitutor(StrLookup<?> variableResolver) {
303 public StrSubstitutor(final StrLookup<?> variableResolver) {
255304 this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
256305 }
257306
264313 * @param escape the escape character
265314 * @throws IllegalArgumentException if the prefix or suffix is null
266315 */
267 public StrSubstitutor(StrLookup<?> variableResolver, String prefix, String suffix, char escape) {
316 public StrSubstitutor(final StrLookup<?> variableResolver, final String prefix, final String suffix,
317 final char escape) {
268318 this.setVariableResolver(variableResolver);
269319 this.setVariablePrefix(prefix);
270320 this.setVariableSuffix(suffix);
271321 this.setEscapeChar(escape);
322 this.setValueDelimiterMatcher(DEFAULT_VALUE_DELIMITER);
323 }
324
325 /**
326 * Creates a new instance and initializes it.
327 *
328 * @param variableResolver the variable resolver, may be null
329 * @param prefix the prefix for variables, not null
330 * @param suffix the suffix for variables, not null
331 * @param escape the escape character
332 * @param valueDelimiter the variable default value delimiter string, may be null
333 * @throws IllegalArgumentException if the prefix or suffix is null
334 * @since 3.2
335 */
336 public StrSubstitutor(final StrLookup<?> variableResolver, final String prefix, final String suffix,
337 final char escape, final String valueDelimiter) {
338 this.setVariableResolver(variableResolver);
339 this.setVariablePrefix(prefix);
340 this.setVariableSuffix(suffix);
341 this.setEscapeChar(escape);
342 this.setValueDelimiter(valueDelimiter);
272343 }
273344
274345 /**
281352 * @throws IllegalArgumentException if the prefix or suffix is null
282353 */
283354 public StrSubstitutor(
284 StrLookup<?> variableResolver, StrMatcher prefixMatcher, StrMatcher suffixMatcher, char escape) {
355 final StrLookup<?> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
356 final char escape) {
357 this(variableResolver, prefixMatcher, suffixMatcher, escape, DEFAULT_VALUE_DELIMITER);
358 }
359
360 /**
361 * Creates a new instance and initializes it.
362 *
363 * @param variableResolver the variable resolver, may be null
364 * @param prefixMatcher the prefix for variables, not null
365 * @param suffixMatcher the suffix for variables, not null
366 * @param escape the escape character
367 * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null
368 * @throws IllegalArgumentException if the prefix or suffix is null
369 * @since 3.2
370 */
371 public StrSubstitutor(
372 final StrLookup<?> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
373 final char escape, final StrMatcher valueDelimiterMatcher) {
285374 this.setVariableResolver(variableResolver);
286375 this.setVariablePrefixMatcher(prefixMatcher);
287376 this.setVariableSuffixMatcher(suffixMatcher);
288377 this.setEscapeChar(escape);
378 this.setValueDelimiterMatcher(valueDelimiterMatcher);
289379 }
290380
291381 //-----------------------------------------------------------------------
296386 * @param source the string to replace in, null returns null
297387 * @return the result of the replace operation
298388 */
299 public String replace(String source) {
389 public String replace(final String source) {
300390 if (source == null) {
301391 return null;
302392 }
303 StrBuilder buf = new StrBuilder(source);
393 final StrBuilder buf = new StrBuilder(source);
304394 if (substitute(buf, 0, source.length()) == false) {
305395 return source;
306396 }
319409 * @param length the length within the array to be processed, must be valid
320410 * @return the result of the replace operation
321411 */
322 public String replace(String source, int offset, int length) {
412 public String replace(final String source, final int offset, final int length) {
323413 if (source == null) {
324414 return null;
325415 }
326 StrBuilder buf = new StrBuilder(length).append(source, offset, length);
416 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
327417 if (substitute(buf, 0, length) == false) {
328418 return source.substring(offset, offset + length);
329419 }
339429 * @param source the character array to replace in, not altered, null returns null
340430 * @return the result of the replace operation
341431 */
342 public String replace(char[] source) {
432 public String replace(final char[] source) {
343433 if (source == null) {
344434 return null;
345435 }
346 StrBuilder buf = new StrBuilder(source.length).append(source);
436 final StrBuilder buf = new StrBuilder(source.length).append(source);
347437 substitute(buf, 0, source.length);
348438 return buf.toString();
349439 }
361451 * @param length the length within the array to be processed, must be valid
362452 * @return the result of the replace operation
363453 */
364 public String replace(char[] source, int offset, int length) {
454 public String replace(final char[] source, final int offset, final int length) {
455 if (source == null) {
456 return null;
457 }
458 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
459 substitute(buf, 0, length);
460 return buf.toString();
461 }
462
463 //-----------------------------------------------------------------------
464 /**
465 * Replaces all the occurrences of variables with their matching values
466 * from the resolver using the given source buffer as a template.
467 * The buffer is not altered by this method.
468 *
469 * @param source the buffer to use as a template, not changed, null returns null
470 * @return the result of the replace operation
471 */
472 public String replace(final StringBuffer source) {
473 if (source == null) {
474 return null;
475 }
476 final StrBuilder buf = new StrBuilder(source.length()).append(source);
477 substitute(buf, 0, buf.length());
478 return buf.toString();
479 }
480
481 /**
482 * Replaces all the occurrences of variables with their matching values
483 * from the resolver using the given source buffer as a template.
484 * The buffer is not altered by this method.
485 * <p>
486 * Only the specified portion of the buffer will be processed.
487 * The rest of the buffer is not processed, and is not returned.
488 *
489 * @param source the buffer to use as a template, not changed, null returns null
490 * @param offset the start offset within the array, must be valid
491 * @param length the length within the array to be processed, must be valid
492 * @return the result of the replace operation
493 */
494 public String replace(final StringBuffer source, final int offset, final int length) {
495 if (source == null) {
496 return null;
497 }
498 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
499 substitute(buf, 0, length);
500 return buf.toString();
501 }
502
503 /**
504 * Replaces all the occurrences of variables with their matching values
505 * from the resolver using the given source as a template.
506 * The source is not altered by this method.
507 *
508 * @param source the buffer to use as a template, not changed, null returns null
509 * @return the result of the replace operation
510 * @since 3.2
511 */
512 public String replace(CharSequence source) {
513 if (source == null) {
514 return null;
515 }
516 return replace(source, 0, source.length());
517 }
518
519 /**
520 * Replaces all the occurrences of variables with their matching values
521 * from the resolver using the given source as a template.
522 * The source is not altered by this method.
523 * <p>
524 * Only the specified portion of the buffer will be processed.
525 * The rest of the buffer is not processed, and is not returned.
526 *
527 * @param source the buffer to use as a template, not changed, null returns null
528 * @param offset the start offset within the array, must be valid
529 * @param length the length within the array to be processed, must be valid
530 * @return the result of the replace operation
531 * @since 3.2
532 */
533 public String replace(CharSequence source, int offset, int length) {
365534 if (source == null) {
366535 return null;
367536 }
373542 //-----------------------------------------------------------------------
374543 /**
375544 * Replaces all the occurrences of variables with their matching values
376 * from the resolver using the given source buffer as a template.
377 * The buffer is not altered by this method.
378 *
379 * @param source the buffer to use as a template, not changed, null returns null
380 * @return the result of the replace operation
381 */
382 public String replace(StringBuffer source) {
545 * from the resolver using the given source builder as a template.
546 * The builder is not altered by this method.
547 *
548 * @param source the builder to use as a template, not changed, null returns null
549 * @return the result of the replace operation
550 */
551 public String replace(final StrBuilder source) {
383552 if (source == null) {
384553 return null;
385554 }
386 StrBuilder buf = new StrBuilder(source.length()).append(source);
555 final StrBuilder buf = new StrBuilder(source.length()).append(source);
387556 substitute(buf, 0, buf.length());
388557 return buf.toString();
389558 }
390559
391 /**
392 * Replaces all the occurrences of variables with their matching values
393 * from the resolver using the given source buffer as a template.
394 * The buffer is not altered by this method.
395 * <p>
396 * Only the specified portion of the buffer will be processed.
397 * The rest of the buffer is not processed, and is not returned.
398 *
399 * @param source the buffer to use as a template, not changed, null returns null
400 * @param offset the start offset within the array, must be valid
401 * @param length the length within the array to be processed, must be valid
402 * @return the result of the replace operation
403 */
404 public String replace(StringBuffer source, int offset, int length) {
405 if (source == null) {
406 return null;
407 }
408 StrBuilder buf = new StrBuilder(length).append(source, offset, length);
409 substitute(buf, 0, length);
410 return buf.toString();
411 }
412
413 //-----------------------------------------------------------------------
414560 /**
415561 * Replaces all the occurrences of variables with their matching values
416562 * from the resolver using the given source builder as a template.
417563 * The builder is not altered by this method.
418 *
419 * @param source the builder to use as a template, not changed, null returns null
420 * @return the result of the replace operation
421 */
422 public String replace(StrBuilder source) {
423 if (source == null) {
424 return null;
425 }
426 StrBuilder buf = new StrBuilder(source.length()).append(source);
427 substitute(buf, 0, buf.length());
428 return buf.toString();
429 }
430
431 /**
432 * Replaces all the occurrences of variables with their matching values
433 * from the resolver using the given source builder as a template.
434 * The builder is not altered by this method.
435564 * <p>
436565 * Only the specified portion of the builder will be processed.
437566 * The rest of the builder is not processed, and is not returned.
441570 * @param length the length within the array to be processed, must be valid
442571 * @return the result of the replace operation
443572 */
444 public String replace(StrBuilder source, int offset, int length) {
573 public String replace(final StrBuilder source, final int offset, final int length) {
445574 if (source == null) {
446575 return null;
447576 }
448 StrBuilder buf = new StrBuilder(length).append(source, offset, length);
577 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
449578 substitute(buf, 0, length);
450579 return buf.toString();
451580 }
459588 * @param source the source to replace in, null returns null
460589 * @return the result of the replace operation
461590 */
462 public String replace(Object source) {
591 public String replace(final Object source) {
463592 if (source == null) {
464593 return null;
465594 }
466 StrBuilder buf = new StrBuilder().append(source);
595 final StrBuilder buf = new StrBuilder().append(source);
467596 substitute(buf, 0, buf.length());
468597 return buf.toString();
469598 }
477606 * @param source the buffer to replace in, updated, null returns zero
478607 * @return true if altered
479608 */
480 public boolean replaceIn(StringBuffer source) {
609 public boolean replaceIn(final StringBuffer source) {
481610 if (source == null) {
482611 return false;
483612 }
497626 * @param length the length within the buffer to be processed, must be valid
498627 * @return true if altered
499628 */
500 public boolean replaceIn(StringBuffer source, int offset, int length) {
629 public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
630 if (source == null) {
631 return false;
632 }
633 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
634 if (substitute(buf, 0, length) == false) {
635 return false;
636 }
637 source.replace(offset, offset + length, buf.toString());
638 return true;
639 }
640
641 //-----------------------------------------------------------------------
642 /**
643 * Replaces all the occurrences of variables within the given source buffer
644 * with their matching values from the resolver.
645 * The buffer is updated with the result.
646 *
647 * @param source the buffer to replace in, updated, null returns zero
648 * @return true if altered
649 * @since 3.2
650 */
651 public boolean replaceIn(StringBuilder source) {
652 if (source == null) {
653 return false;
654 }
655 return replaceIn(source, 0, source.length());
656 }
657
658 /**
659 * Replaces all the occurrences of variables within the given source builder
660 * with their matching values from the resolver.
661 * The builder is updated with the result.
662 * <p>
663 * Only the specified portion of the buffer will be processed.
664 * The rest of the buffer is not processed, but it is not deleted.
665 *
666 * @param source the buffer to replace in, updated, null returns zero
667 * @param offset the start offset within the array, must be valid
668 * @param length the length within the buffer to be processed, must be valid
669 * @return true if altered
670 * @since 3.2
671 */
672 public boolean replaceIn(StringBuilder source, int offset, int length) {
501673 if (source == null) {
502674 return false;
503675 }
517689 * @param source the builder to replace in, updated, null returns zero
518690 * @return true if altered
519691 */
520 public boolean replaceIn(StrBuilder source) {
692 public boolean replaceIn(final StrBuilder source) {
521693 if (source == null) {
522694 return false;
523695 }
536708 * @param length the length within the builder to be processed, must be valid
537709 * @return true if altered
538710 */
539 public boolean replaceIn(StrBuilder source, int offset, int length) {
711 public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
540712 if (source == null) {
541713 return false;
542714 }
558730 * @param length the length within the builder to be processed, must be valid
559731 * @return true if altered
560732 */
561 protected boolean substitute(StrBuilder buf, int offset, int length) {
733 protected boolean substitute(final StrBuilder buf, final int offset, final int length) {
562734 return substitute(buf, offset, length, null) > 0;
563735 }
564736
574746 * @return the length change that occurs, unless priorVariables is null when the int
575747 * represents a boolean flag as to whether any change occurred.
576748 */
577 private int substitute(StrBuilder buf, int offset, int length, List<String> priorVariables) {
578 StrMatcher prefixMatcher = getVariablePrefixMatcher();
579 StrMatcher suffixMatcher = getVariableSuffixMatcher();
580 char escape = getEscapeChar();
581
582 boolean top = priorVariables == null;
749 private int substitute(final StrBuilder buf, final int offset, final int length, List<String> priorVariables) {
750 final StrMatcher pfxMatcher = getVariablePrefixMatcher();
751 final StrMatcher suffMatcher = getVariableSuffixMatcher();
752 final char escape = getEscapeChar();
753 final StrMatcher valueDelimMatcher = getValueDelimiterMatcher();
754 final boolean substitutionInVariablesEnabled = isEnableSubstitutionInVariables();
755
756 final boolean top = priorVariables == null;
583757 boolean altered = false;
584758 int lengthChange = 0;
585759 char[] chars = buf.buffer;
586760 int bufEnd = offset + length;
587761 int pos = offset;
588762 while (pos < bufEnd) {
589 int startMatchLen = prefixMatcher.isMatch(chars, pos, offset,
763 final int startMatchLen = pfxMatcher.isMatch(chars, pos, offset,
590764 bufEnd);
591765 if (startMatchLen == 0) {
592766 pos++;
601775 bufEnd--;
602776 } else {
603777 // find suffix
604 int startPos = pos;
778 final int startPos = pos;
605779 pos += startMatchLen;
606780 int endMatchLen = 0;
607781 int nestedVarCount = 0;
608782 while (pos < bufEnd) {
609 if (isEnableSubstitutionInVariables()
610 && (endMatchLen = prefixMatcher.isMatch(chars,
783 if (substitutionInVariablesEnabled
784 && (endMatchLen = pfxMatcher.isMatch(chars,
611785 pos, offset, bufEnd)) != 0) {
612786 // found a nested variable start
613787 nestedVarCount++;
615789 continue;
616790 }
617791
618 endMatchLen = suffixMatcher.isMatch(chars, pos, offset,
792 endMatchLen = suffMatcher.isMatch(chars, pos, offset,
619793 bufEnd);
620794 if (endMatchLen == 0) {
621795 pos++;
622796 } else {
623797 // found variable end marker
624798 if (nestedVarCount == 0) {
625 String varName = new String(chars, startPos
799 String varNameExpr = new String(chars, startPos
626800 + startMatchLen, pos - startPos
627801 - startMatchLen);
628 if (isEnableSubstitutionInVariables()) {
629 StrBuilder bufName = new StrBuilder(varName);
802 if (substitutionInVariablesEnabled) {
803 final StrBuilder bufName = new StrBuilder(varNameExpr);
630804 substitute(bufName, 0, bufName.length());
631 varName = bufName.toString();
805 varNameExpr = bufName.toString();
632806 }
633807 pos += endMatchLen;
634 int endPos = pos;
808 final int endPos = pos;
809
810 String varName = varNameExpr;
811 String varDefaultValue = null;
812
813 if (valueDelimMatcher != null) {
814 final char [] varNameExprChars = varNameExpr.toCharArray();
815 int valueDelimiterMatchLen = 0;
816 for (int i = 0; i < varNameExprChars.length; i++) {
817 // if there's any nested variable when nested variable substitution disabled, then stop resolving name and default value.
818 if (!substitutionInVariablesEnabled
819 && pfxMatcher.isMatch(varNameExprChars, i, i, varNameExprChars.length) != 0) {
820 break;
821 }
822 if ((valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i)) != 0) {
823 varName = varNameExpr.substring(0, i);
824 varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen);
825 break;
826 }
827 }
828 }
635829
636830 // on the first call initialize priorVariables
637831 if (priorVariables == null) {
647841 // resolve the variable
648842 String varValue = resolveVariable(varName, buf,
649843 startPos, endPos);
844 if (varValue == null) {
845 varValue = varDefaultValue;
846 }
650847 if (varValue != null) {
651848 // recursive replace
652 int varLen = varValue.length();
849 final int varLen = varValue.length();
653850 buf.replace(startPos, endPos, varValue);
654851 altered = true;
655852 int change = substitute(buf, startPos,
688885 * @param varName the variable name to check
689886 * @param priorVariables the list of prior variables
690887 */
691 private void checkCyclicSubstitution(String varName, List<String> priorVariables) {
888 private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
692889 if (priorVariables.contains(varName) == false) {
693890 return;
694891 }
695 StrBuilder buf = new StrBuilder(256);
892 final StrBuilder buf = new StrBuilder(256);
696893 buf.append("Infinite loop in property interpolation of ");
697894 buf.append(priorVariables.remove(0));
698895 buf.append(": ");
717914 * @param endPos the end position of the variable including the suffix, valid
718915 * @return the variable's value or <b>null</b> if the variable is unknown
719916 */
720 protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) {
721 StrLookup<?> resolver = getVariableResolver();
917 protected String resolveVariable(final String variableName, final StrBuilder buf, final int startPos, final int endPos) {
918 final StrLookup<?> resolver = getVariableResolver();
722919 if (resolver == null) {
723920 return null;
724921 }
743940 *
744941 * @param escapeCharacter the escape character (0 for disabling escaping)
745942 */
746 public void setEscapeChar(char escapeCharacter) {
943 public void setEscapeChar(final char escapeCharacter) {
747944 this.escapeChar = escapeCharacter;
748945 }
749946
773970 * @return this, to enable chaining
774971 * @throws IllegalArgumentException if the prefix matcher is null
775972 */
776 public StrSubstitutor setVariablePrefixMatcher(StrMatcher prefixMatcher) {
973 public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
777974 if (prefixMatcher == null) {
778975 throw new IllegalArgumentException("Variable prefix matcher must not be null!");
779976 }
791988 * @param prefix the prefix character to use
792989 * @return this, to enable chaining
793990 */
794 public StrSubstitutor setVariablePrefix(char prefix) {
991 public StrSubstitutor setVariablePrefix(final char prefix) {
795992 return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
796993 }
797994
8051002 * @return this, to enable chaining
8061003 * @throws IllegalArgumentException if the prefix is null
8071004 */
808 public StrSubstitutor setVariablePrefix(String prefix) {
1005 public StrSubstitutor setVariablePrefix(final String prefix) {
8091006 if (prefix == null) {
8101007 throw new IllegalArgumentException("Variable prefix must not be null!");
8111008 }
8381035 * @return this, to enable chaining
8391036 * @throws IllegalArgumentException if the suffix matcher is null
8401037 */
841 public StrSubstitutor setVariableSuffixMatcher(StrMatcher suffixMatcher) {
1038 public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
8421039 if (suffixMatcher == null) {
8431040 throw new IllegalArgumentException("Variable suffix matcher must not be null!");
8441041 }
8561053 * @param suffix the suffix character to use
8571054 * @return this, to enable chaining
8581055 */
859 public StrSubstitutor setVariableSuffix(char suffix) {
1056 public StrSubstitutor setVariableSuffix(final char suffix) {
8601057 return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
8611058 }
8621059
8701067 * @return this, to enable chaining
8711068 * @throws IllegalArgumentException if the suffix is null
8721069 */
873 public StrSubstitutor setVariableSuffix(String suffix) {
1070 public StrSubstitutor setVariableSuffix(final String suffix) {
8741071 if (suffix == null) {
8751072 throw new IllegalArgumentException("Variable suffix must not be null!");
8761073 }
8771074 return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix));
8781075 }
8791076
1077 // Variable Default Value Delimiter
1078 //-----------------------------------------------------------------------
1079 /**
1080 * Gets the variable default value delimiter matcher currently in use.
1081 * <p>
1082 * The variable default value delimiter is the characer or characters that delimite the
1083 * variable name and the variable default value. This delimiter is expressed in terms of a matcher
1084 * allowing advanced variable default value delimiter matches.
1085 * <p>
1086 * If it returns null, then the variable default value resolution is disabled.
1087 *
1088 * @return the variable default value delimiter matcher in use, may be null
1089 * @since 3.2
1090 */
1091 public StrMatcher getValueDelimiterMatcher() {
1092 return valueDelimiterMatcher;
1093 }
1094
1095 /**
1096 * Sets the variable default value delimiter matcher to use.
1097 * <p>
1098 * The variable default value delimiter is the characer or characters that delimite the
1099 * variable name and the variable default value. This delimiter is expressed in terms of a matcher
1100 * allowing advanced variable default value delimiter matches.
1101 * <p>
1102 * If the <code>valueDelimiterMatcher</code> is null, then the variable default value resolution
1103 * becomes disabled.
1104 *
1105 * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
1106 * @return this, to enable chaining
1107 * @since 3.2
1108 */
1109 public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) {
1110 this.valueDelimiterMatcher = valueDelimiterMatcher;
1111 return this;
1112 }
1113
1114 /**
1115 * Sets the variable default value delimiter to use.
1116 * <p>
1117 * The variable default value delimiter is the characer or characters that delimite the
1118 * variable name and the variable default value. This method allows a single character
1119 * variable default value delimiter to be easily set.
1120 *
1121 * @param valueDelimiter the variable default value delimiter character to use
1122 * @return this, to enable chaining
1123 * @since 3.2
1124 */
1125 public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
1126 return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter));
1127 }
1128
1129 /**
1130 * Sets the variable default value delimiter to use.
1131 * <p>
1132 * The variable default value delimiter is the characer or characters that delimite the
1133 * variable name and the variable default value. This method allows a string
1134 * variable default value delimiter to be easily set.
1135 * <p>
1136 * If the <code>valueDelimiter</code> is null or empty string, then the variable default
1137 * value resolution becomes disabled.
1138 *
1139 * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
1140 * @return this, to enable chaining
1141 * @since 3.2
1142 */
1143 public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
1144 if (StringUtils.isEmpty(valueDelimiter)) {
1145 setValueDelimiterMatcher(null);
1146 return this;
1147 }
1148 return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter));
1149 }
1150
8801151 // Resolver
8811152 //-----------------------------------------------------------------------
8821153 /**
8931164 *
8941165 * @param variableResolver the VariableResolver
8951166 */
896 public void setVariableResolver(StrLookup<?> variableResolver) {
1167 public void setVariableResolver(final StrLookup<?> variableResolver) {
8971168 this.variableResolver = variableResolver;
8981169 }
8991170
9191190 * @since 3.0
9201191 */
9211192 public void setEnableSubstitutionInVariables(
922 boolean enableSubstitutionInVariables) {
1193 final boolean enableSubstitutionInVariables) {
9231194 this.enableSubstitutionInVariables = enableSubstitutionInVariables;
9241195 }
9251196 }
2222 import java.util.NoSuchElementException;
2323
2424 import org.apache.commons.lang3.ArrayUtils;
25 import org.apache.commons.lang3.StringUtils;
2526
2627 /**
2728 * Tokenizes a string based based on delimiters (separators)
8182 * </table>
8283 *
8384 * @since 2.2
84 * @version $Id: StrTokenizer.java 1199894 2011-11-09 17:53:59Z ggregory $
85 * @version $Id: StrTokenizer.java 1533551 2013-10-18 16:49:15Z sebb $
8586 */
8687 public class StrTokenizer implements ListIterator<String>, Cloneable {
8788
159160 * @param input the text to parse
160161 * @return a new tokenizer instance which parses Comma Separated Value strings
161162 */
162 public static StrTokenizer getCSVInstance(String input) {
163 StrTokenizer tok = getCSVClone();
163 public static StrTokenizer getCSVInstance(final String input) {
164 final StrTokenizer tok = getCSVClone();
164165 tok.reset(input);
165166 return tok;
166167 }
174175 * @param input the text to parse
175176 * @return a new tokenizer instance which parses Comma Separated Value strings
176177 */
177 public static StrTokenizer getCSVInstance(char[] input) {
178 StrTokenizer tok = getCSVClone();
178 public static StrTokenizer getCSVInstance(final char[] input) {
179 final StrTokenizer tok = getCSVClone();
179180 tok.reset(input);
180181 return tok;
181182 }
209210 * @param input the string to parse
210211 * @return a new tokenizer instance which parses Tab Separated Value strings.
211212 */
212 public static StrTokenizer getTSVInstance(String input) {
213 StrTokenizer tok = getTSVClone();
213 public static StrTokenizer getTSVInstance(final String input) {
214 final StrTokenizer tok = getTSVClone();
214215 tok.reset(input);
215216 return tok;
216217 }
222223 * @param input the string to parse
223224 * @return a new tokenizer instance which parses Tab Separated Value strings.
224225 */
225 public static StrTokenizer getTSVInstance(char[] input) {
226 StrTokenizer tok = getTSVClone();
226 public static StrTokenizer getTSVInstance(final char[] input) {
227 final StrTokenizer tok = getTSVClone();
227228 tok.reset(input);
228229 return tok;
229230 }
246247 *
247248 * @param input the string which is to be parsed
248249 */
249 public StrTokenizer(String input) {
250 public StrTokenizer(final String input) {
250251 super();
251252 if (input != null) {
252253 chars = input.toCharArray();
261262 * @param input the string which is to be parsed
262263 * @param delim the field delimiter character
263264 */
264 public StrTokenizer(String input, char delim) {
265 public StrTokenizer(final String input, final char delim) {
265266 this(input);
266267 setDelimiterChar(delim);
267268 }
272273 * @param input the string which is to be parsed
273274 * @param delim the field delimiter string
274275 */
275 public StrTokenizer(String input, String delim) {
276 public StrTokenizer(final String input, final String delim) {
276277 this(input);
277278 setDelimiterString(delim);
278279 }
283284 * @param input the string which is to be parsed
284285 * @param delim the field delimiter matcher
285286 */
286 public StrTokenizer(String input, StrMatcher delim) {
287 public StrTokenizer(final String input, final StrMatcher delim) {
287288 this(input);
288289 setDelimiterMatcher(delim);
289290 }
296297 * @param delim the field delimiter character
297298 * @param quote the field quoted string character
298299 */
299 public StrTokenizer(String input, char delim, char quote) {
300 public StrTokenizer(final String input, final char delim, final char quote) {
300301 this(input, delim);
301302 setQuoteChar(quote);
302303 }
309310 * @param delim the field delimiter matcher
310311 * @param quote the field quoted string matcher
311312 */
312 public StrTokenizer(String input, StrMatcher delim, StrMatcher quote) {
313 public StrTokenizer(final String input, final StrMatcher delim, final StrMatcher quote) {
313314 this(input, delim);
314315 setQuoteMatcher(quote);
315316 }
320321 *
321322 * @param input the string which is to be parsed, not cloned
322323 */
323 public StrTokenizer(char[] input) {
324 public StrTokenizer(final char[] input) {
324325 super();
325326 this.chars = ArrayUtils.clone(input);
326327 }
331332 * @param input the string which is to be parsed, not cloned
332333 * @param delim the field delimiter character
333334 */
334 public StrTokenizer(char[] input, char delim) {
335 public StrTokenizer(final char[] input, final char delim) {
335336 this(input);
336337 setDelimiterChar(delim);
337338 }
342343 * @param input the string which is to be parsed, not cloned
343344 * @param delim the field delimiter string
344345 */
345 public StrTokenizer(char[] input, String delim) {
346 public StrTokenizer(final char[] input, final String delim) {
346347 this(input);
347348 setDelimiterString(delim);
348349 }
353354 * @param input the string which is to be parsed, not cloned
354355 * @param delim the field delimiter matcher
355356 */
356 public StrTokenizer(char[] input, StrMatcher delim) {
357 public StrTokenizer(final char[] input, final StrMatcher delim) {
357358 this(input);
358359 setDelimiterMatcher(delim);
359360 }
366367 * @param delim the field delimiter character
367368 * @param quote the field quoted string character
368369 */
369 public StrTokenizer(char[] input, char delim, char quote) {
370 public StrTokenizer(final char[] input, final char delim, final char quote) {
370371 this(input, delim);
371372 setQuoteChar(quote);
372373 }
379380 * @param delim the field delimiter character
380381 * @param quote the field quoted string character
381382 */
382 public StrTokenizer(char[] input, StrMatcher delim, StrMatcher quote) {
383 public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) {
383384 this(input, delim);
384385 setQuoteMatcher(quote);
385386 }
439440 */
440441 public List<String> getTokenList() {
441442 checkTokenized();
442 List<String> list = new ArrayList<String>(tokens.length);
443 for (String element : tokens) {
443 final List<String> list = new ArrayList<String>(tokens.length);
444 for (final String element : tokens) {
444445 list.add(element);
445446 }
446447 return list;
467468 * @param input the new string to tokenize, null sets no text to parse
468469 * @return this, to enable chaining
469470 */
470 public StrTokenizer reset(String input) {
471 public StrTokenizer reset(final String input) {
471472 reset();
472473 if (input != null) {
473474 this.chars = input.toCharArray();
485486 * @param input the new character array to tokenize, not cloned, null sets no text to parse
486487 * @return this, to enable chaining
487488 */
488 public StrTokenizer reset(char[] input) {
489 public StrTokenizer reset(final char[] input) {
489490 reset();
490491 this.chars = ArrayUtils.clone(input);
491492 return this;
498499 *
499500 * @return true if there are more tokens
500501 */
502 @Override
501503 public boolean hasNext() {
502504 checkTokenized();
503505 return tokenPos < tokens.length;
509511 * @return the next String token
510512 * @throws NoSuchElementException if there are no more elements
511513 */
514 @Override
512515 public String next() {
513516 if (hasNext()) {
514517 return tokens[tokenPos++];
521524 *
522525 * @return the next token index
523526 */
527 @Override
524528 public int nextIndex() {
525529 return tokenPos;
526530 }
530534 *
531535 * @return true if there are previous tokens
532536 */
537 @Override
533538 public boolean hasPrevious() {
534539 checkTokenized();
535540 return tokenPos > 0;
540545 *
541546 * @return the previous token
542547 */
548 @Override
543549 public String previous() {
544550 if (hasPrevious()) {
545551 return tokens[--tokenPos];
552558 *
553559 * @return the previous token index
554560 */
561 @Override
555562 public int previousIndex() {
556563 return tokenPos - 1;
557564 }
561568 *
562569 * @throws UnsupportedOperationException always
563570 */
571 @Override
564572 public void remove() {
565573 throw new UnsupportedOperationException("remove() is unsupported");
566574 }
570578 * @param obj this parameter ignored.
571579 * @throws UnsupportedOperationException always
572580 */
573 public void set(String obj) {
581 @Override
582 public void set(final String obj) {
574583 throw new UnsupportedOperationException("set() is unsupported");
575584 }
576585
579588 * @param obj this parameter ignored.
580589 * @throws UnsupportedOperationException always
581590 */
582 public void add(String obj) {
591 @Override
592 public void add(final String obj) {
583593 throw new UnsupportedOperationException("add() is unsupported");
584594 }
585595
592602 if (tokens == null) {
593603 if (chars == null) {
594604 // still call tokenize as subclass may do some work
595 List<String> split = tokenize(null, 0, 0);
605 final List<String> split = tokenize(null, 0, 0);
596606 tokens = split.toArray(new String[split.size()]);
597607 } else {
598 List<String> split = tokenize(chars, 0, chars.length);
608 final List<String> split = tokenize(chars, 0, chars.length);
599609 tokens = split.toArray(new String[split.size()]);
600610 }
601611 }
616626 * equal to the length of the array to this method, however a subclass
617627 * may pass other values, or even an entirely different array.
618628 *
619 * @param chars the character array being tokenized, may be null
629 * @param srcChars the character array being tokenized, may be null
620630 * @param offset the start position within the character array, must be valid
621631 * @param count the number of characters to tokenize, must be valid
622632 * @return the modifiable list of String tokens, unmodifiable if null array or zero count
623633 */
624 protected List<String> tokenize(char[] chars, int offset, int count) {
625 if (chars == null || count == 0) {
634 protected List<String> tokenize(final char[] srcChars, final int offset, final int count) {
635 if (srcChars == null || count == 0) {
626636 return Collections.emptyList();
627637 }
628 StrBuilder buf = new StrBuilder();
629 List<String> tokens = new ArrayList<String>();
638 final StrBuilder buf = new StrBuilder();
639 final List<String> tokenList = new ArrayList<String>();
630640 int pos = offset;
631641
632642 // loop around the entire buffer
633643 while (pos >= 0 && pos < count) {
634644 // find next token
635 pos = readNextToken(chars, pos, count, buf, tokens);
645 pos = readNextToken(srcChars, pos, count, buf, tokenList);
636646
637647 // handle case where end of string is a delimiter
638648 if (pos >= count) {
639 addToken(tokens, "");
649 addToken(tokenList, "");
640650 }
641651 }
642 return tokens;
652 return tokenList;
643653 }
644654
645655 /**
648658 * @param list the list to add to
649659 * @param tok the token to add
650660 */
651 private void addToken(List<String> list, String tok) {
652 if (tok == null || tok.length() == 0) {
661 private void addToken(final List<String> list, String tok) {
662 if (StringUtils.isEmpty(tok)) {
653663 if (isIgnoreEmptyTokens()) {
654664 return;
655665 }
663673 /**
664674 * Reads character by character through the String to get the next token.
665675 *
666 * @param chars the character array being tokenized
676 * @param srcChars the character array being tokenized
667677 * @param start the first character of field
668678 * @param len the length of the character array being tokenized
669679 * @param workArea a temporary work area
670 * @param tokens the list of parsed tokens
680 * @param tokenList the list of parsed tokens
671681 * @return the starting position of the next field (the character
672682 * immediately after the delimiter), or -1 if end of string found
673683 */
674 private int readNextToken(char[] chars, int start, int len, StrBuilder workArea, List<String> tokens) {
684 private int readNextToken(final char[] srcChars, int start, final int len, final StrBuilder workArea, final List<String> tokenList) {
675685 // skip all leading whitespace, unless it is the
676686 // field delimiter or the quote character
677687 while (start < len) {
678 int removeLen = Math.max(
679 getIgnoredMatcher().isMatch(chars, start, start, len),
680 getTrimmerMatcher().isMatch(chars, start, start, len));
688 final int removeLen = Math.max(
689 getIgnoredMatcher().isMatch(srcChars, start, start, len),
690 getTrimmerMatcher().isMatch(srcChars, start, start, len));
681691 if (removeLen == 0 ||
682 getDelimiterMatcher().isMatch(chars, start, start, len) > 0 ||
683 getQuoteMatcher().isMatch(chars, start, start, len) > 0) {
692 getDelimiterMatcher().isMatch(srcChars, start, start, len) > 0 ||
693 getQuoteMatcher().isMatch(srcChars, start, start, len) > 0) {
684694 break;
685695 }
686696 start += removeLen;
688698
689699 // handle reaching end
690700 if (start >= len) {
691 addToken(tokens, "");
701 addToken(tokenList, "");
692702 return -1;
693703 }
694704
695705 // handle empty token
696 int delimLen = getDelimiterMatcher().isMatch(chars, start, start, len);
706 final int delimLen = getDelimiterMatcher().isMatch(srcChars, start, start, len);
697707 if (delimLen > 0) {
698 addToken(tokens, "");
708 addToken(tokenList, "");
699709 return start + delimLen;
700710 }
701711
702712 // handle found token
703 int quoteLen = getQuoteMatcher().isMatch(chars, start, start, len);
713 final int quoteLen = getQuoteMatcher().isMatch(srcChars, start, start, len);
704714 if (quoteLen > 0) {
705 return readWithQuotes(chars, start + quoteLen, len, workArea, tokens, start, quoteLen);
706 }
707 return readWithQuotes(chars, start, len, workArea, tokens, 0, 0);
715 return readWithQuotes(srcChars, start + quoteLen, len, workArea, tokenList, start, quoteLen);
716 }
717 return readWithQuotes(srcChars, start, len, workArea, tokenList, 0, 0);
708718 }
709719
710720 /**
711721 * Reads a possibly quoted string token.
712722 *
713 * @param chars the character array being tokenized
723 * @param srcChars the character array being tokenized
714724 * @param start the first character of field
715725 * @param len the length of the character array being tokenized
716726 * @param workArea a temporary work area
717 * @param tokens the list of parsed tokens
727 * @param tokenList the list of parsed tokens
718728 * @param quoteStart the start position of the matched quote, 0 if no quoting
719729 * @param quoteLen the length of the matched quote, 0 if no quoting
720730 * @return the starting position of the next field (the character
721731 * immediately after the delimiter, or if end of string found,
722732 * then the length of string
723733 */
724 private int readWithQuotes(char[] chars, int start, int len, StrBuilder workArea,
725 List<String> tokens, int quoteStart, int quoteLen) {
734 private int readWithQuotes(final char[] srcChars, final int start, final int len, final StrBuilder workArea,
735 final List<String> tokenList, final int quoteStart, final int quoteLen) {
726736 // Loop until we've found the end of the quoted
727737 // string or the end of the input
728738 workArea.clear();
741751 // followed by a second quote. If so, then we need
742752 // to actually put the quote character into the token
743753 // rather than end the token.
744 if (isQuote(chars, pos, len, quoteStart, quoteLen)) {
745 if (isQuote(chars, pos + quoteLen, len, quoteStart, quoteLen)) {
754 if (isQuote(srcChars, pos, len, quoteStart, quoteLen)) {
755 if (isQuote(srcChars, pos + quoteLen, len, quoteStart, quoteLen)) {
746756 // matched pair of quotes, thus an escaped quote
747 workArea.append(chars, pos, quoteLen);
757 workArea.append(srcChars, pos, quoteLen);
748758 pos += quoteLen * 2;
749759 trimStart = workArea.size();
750760 continue;
757767 }
758768
759769 // copy regular character from inside quotes
760 workArea.append(chars[pos++]);
770 workArea.append(srcChars[pos++]);
761771 trimStart = workArea.size();
762772
763773 } else {
764774 // Not in quoting mode
765775
766776 // check for delimiter, and thus end of token
767 int delimLen = getDelimiterMatcher().isMatch(chars, pos, start, len);
777 final int delimLen = getDelimiterMatcher().isMatch(srcChars, pos, start, len);
768778 if (delimLen > 0) {
769779 // return condition when end of token found
770 addToken(tokens, workArea.substring(0, trimStart));
780 addToken(tokenList, workArea.substring(0, trimStart));
771781 return pos + delimLen;
772782 }
773783
774784 // check for quote, and thus back into quoting mode
775 if (quoteLen > 0 && isQuote(chars, pos, len, quoteStart, quoteLen)) {
785 if (quoteLen > 0 && isQuote(srcChars, pos, len, quoteStart, quoteLen)) {
776786 quoting = true;
777787 pos += quoteLen;
778788 continue;
779789 }
780790
781791 // check for ignored (outside quotes), and ignore
782 int ignoredLen = getIgnoredMatcher().isMatch(chars, pos, start, len);
792 final int ignoredLen = getIgnoredMatcher().isMatch(srcChars, pos, start, len);
783793 if (ignoredLen > 0) {
784794 pos += ignoredLen;
785795 continue;
788798 // check for trimmed character
789799 // don't yet know if its at the end, so copy to workArea
790800 // use trimStart to keep track of trim at the end
791 int trimmedLen = getTrimmerMatcher().isMatch(chars, pos, start, len);
801 final int trimmedLen = getTrimmerMatcher().isMatch(srcChars, pos, start, len);
792802 if (trimmedLen > 0) {
793 workArea.append(chars, pos, trimmedLen);
803 workArea.append(srcChars, pos, trimmedLen);
794804 pos += trimmedLen;
795805 continue;
796806 }
797807
798808 // copy regular character from outside quotes
799 workArea.append(chars[pos++]);
809 workArea.append(srcChars[pos++]);
800810 trimStart = workArea.size();
801811 }
802812 }
803813
804814 // return condition when end of string found
805 addToken(tokens, workArea.substring(0, trimStart));
815 addToken(tokenList, workArea.substring(0, trimStart));
806816 return -1;
807817 }
808818
810820 * Checks if the characters at the index specified match the quote
811821 * already matched in readNextToken().
812822 *
813 * @param chars the character array being tokenized
823 * @param srcChars the character array being tokenized
814824 * @param pos the position to check for a quote
815825 * @param len the length of the character array being tokenized
816826 * @param quoteStart the start position of the matched quote, 0 if no quoting
817827 * @param quoteLen the length of the matched quote, 0 if no quoting
818828 * @return true if a quote is matched
819829 */
820 private boolean isQuote(char[] chars, int pos, int len, int quoteStart, int quoteLen) {
830 private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart, final int quoteLen) {
821831 for (int i = 0; i < quoteLen; i++) {
822 if (pos + i >= len || chars[pos + i] != chars[quoteStart + i]) {
832 if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) {
823833 return false;
824834 }
825835 }
845855 * @param delim the delimiter matcher to use
846856 * @return this, to enable chaining
847857 */
848 public StrTokenizer setDelimiterMatcher(StrMatcher delim) {
858 public StrTokenizer setDelimiterMatcher(final StrMatcher delim) {
849859 if (delim == null) {
850860 this.delimMatcher = StrMatcher.noneMatcher();
851861 } else {
860870 * @param delim the delimiter character to use
861871 * @return this, to enable chaining
862872 */
863 public StrTokenizer setDelimiterChar(char delim) {
873 public StrTokenizer setDelimiterChar(final char delim) {
864874 return setDelimiterMatcher(StrMatcher.charMatcher(delim));
865875 }
866876
870880 * @param delim the delimiter string to use
871881 * @return this, to enable chaining
872882 */
873 public StrTokenizer setDelimiterString(String delim) {
883 public StrTokenizer setDelimiterString(final String delim) {
874884 return setDelimiterMatcher(StrMatcher.stringMatcher(delim));
875885 }
876886
898908 * @param quote the quote matcher to use, null ignored
899909 * @return this, to enable chaining
900910 */
901 public StrTokenizer setQuoteMatcher(StrMatcher quote) {
911 public StrTokenizer setQuoteMatcher(final StrMatcher quote) {
902912 if (quote != null) {
903913 this.quoteMatcher = quote;
904914 }
914924 * @param quote the quote character to use
915925 * @return this, to enable chaining
916926 */
917 public StrTokenizer setQuoteChar(char quote) {
927 public StrTokenizer setQuoteChar(final char quote) {
918928 return setQuoteMatcher(StrMatcher.charMatcher(quote));
919929 }
920930
942952 * @param ignored the ignored matcher to use, null ignored
943953 * @return this, to enable chaining
944954 */
945 public StrTokenizer setIgnoredMatcher(StrMatcher ignored) {
955 public StrTokenizer setIgnoredMatcher(final StrMatcher ignored) {
946956 if (ignored != null) {
947957 this.ignoredMatcher = ignored;
948958 }
958968 * @param ignored the ignored character to use
959969 * @return this, to enable chaining
960970 */
961 public StrTokenizer setIgnoredChar(char ignored) {
971 public StrTokenizer setIgnoredChar(final char ignored) {
962972 return setIgnoredMatcher(StrMatcher.charMatcher(ignored));
963973 }
964974
986996 * @param trimmer the trimmer matcher to use, null ignored
987997 * @return this, to enable chaining
988998 */
989 public StrTokenizer setTrimmerMatcher(StrMatcher trimmer) {
999 public StrTokenizer setTrimmerMatcher(final StrMatcher trimmer) {
9901000 if (trimmer != null) {
9911001 this.trimmerMatcher = trimmer;
9921002 }
10111021 * @param emptyAsNull whether empty tokens are returned as null
10121022 * @return this, to enable chaining
10131023 */
1014 public StrTokenizer setEmptyTokenAsNull(boolean emptyAsNull) {
1024 public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
10151025 this.emptyAsNull = emptyAsNull;
10161026 return this;
10171027 }
10341044 * @param ignoreEmptyTokens whether empty tokens are not returned
10351045 * @return this, to enable chaining
10361046 */
1037 public StrTokenizer setIgnoreEmptyTokens(boolean ignoreEmptyTokens) {
1047 public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
10381048 this.ignoreEmptyTokens = ignoreEmptyTokens;
10391049 return this;
10401050 }
10641074 public Object clone() {
10651075 try {
10661076 return cloneReset();
1067 } catch (CloneNotSupportedException ex) {
1077 } catch (final CloneNotSupportedException ex) {
10681078 return null;
10691079 }
10701080 }
10781088 */
10791089 Object cloneReset() throws CloneNotSupportedException {
10801090 // this method exists to enable 100% test coverage
1081 StrTokenizer cloned = (StrTokenizer) super.clone();
1091 final StrTokenizer cloned = (StrTokenizer) super.clone();
10821092 if (cloned.chars != null) {
10831093 cloned.chars = cloned.chars.clone();
10841094 }
2626 * Each method documents its behaviour in more detail.</p>
2727 *
2828 * @since 2.0
29 * @version $Id: WordUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
29 * @version $Id: WordUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3030 */
3131 public class WordUtils {
3232
6262 * @param wrapLength the column to wrap the words at, less than 1 is treated as 1
6363 * @return a line with newlines inserted, <code>null</code> if null input
6464 */
65 public static String wrap(String str, int wrapLength) {
65 public static String wrap(final String str, final int wrapLength) {
6666 return wrap(str, wrapLength, null, false);
6767 }
6868
8484 * @param wrapLongWords true if long words (such as URLs) should be wrapped
8585 * @return a line with newlines inserted, <code>null</code> if null input
8686 */
87 public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) {
87 public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords) {
8888 if (str == null) {
8989 return null;
9090 }
9494 if (wrapLength < 1) {
9595 wrapLength = 1;
9696 }
97 int inputLineLength = str.length();
97 final int inputLineLength = str.length();
9898 int offset = 0;
99 StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32);
99 final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32);
100100
101101 while (inputLineLength - offset > wrapLength) {
102102 if (str.charAt(offset) == ' ') {
163163 * @see #uncapitalize(String)
164164 * @see #capitalizeFully(String)
165165 */
166 public static String capitalize(String str) {
166 public static String capitalize(final String str) {
167167 return capitalize(str, null);
168168 }
169169
196196 * @see #capitalizeFully(String)
197197 * @since 2.1
198198 */
199 public static String capitalize(String str, char... delimiters) {
200 int delimLen = delimiters == null ? -1 : delimiters.length;
199 public static String capitalize(final String str, final char... delimiters) {
200 final int delimLen = delimiters == null ? -1 : delimiters.length;
201201 if (StringUtils.isEmpty(str) || delimLen == 0) {
202202 return str;
203203 }
204 char[] buffer = str.toCharArray();
204 final char[] buffer = str.toCharArray();
205205 boolean capitalizeNext = true;
206206 for (int i = 0; i < buffer.length; i++) {
207 char ch = buffer[i];
207 final char ch = buffer[i];
208208 if (isDelimiter(ch, delimiters)) {
209209 capitalizeNext = true;
210210 } else if (capitalizeNext) {
235235 * @param str the String to capitalize, may be null
236236 * @return capitalized String, <code>null</code> if null String input
237237 */
238 public static String capitalizeFully(String str) {
238 public static String capitalizeFully(final String str) {
239239 return capitalizeFully(str, null);
240240 }
241241
265265 * @return capitalized String, <code>null</code> if null String input
266266 * @since 2.1
267267 */
268 public static String capitalizeFully(String str, char... delimiters) {
269 int delimLen = delimiters == null ? -1 : delimiters.length;
268 public static String capitalizeFully(String str, final char... delimiters) {
269 final int delimLen = delimiters == null ? -1 : delimiters.length;
270270 if (StringUtils.isEmpty(str) || delimLen == 0) {
271271 return str;
272272 }
292292 * @return uncapitalized String, <code>null</code> if null String input
293293 * @see #capitalize(String)
294294 */
295 public static String uncapitalize(String str) {
295 public static String uncapitalize(final String str) {
296296 return uncapitalize(str, null);
297297 }
298298
321321 * @see #capitalize(String)
322322 * @since 2.1
323323 */
324 public static String uncapitalize(String str, char... delimiters) {
325 int delimLen = delimiters == null ? -1 : delimiters.length;
324 public static String uncapitalize(final String str, final char... delimiters) {
325 final int delimLen = delimiters == null ? -1 : delimiters.length;
326326 if (StringUtils.isEmpty(str) || delimLen == 0) {
327327 return str;
328328 }
329 char[] buffer = str.toCharArray();
329 final char[] buffer = str.toCharArray();
330330 boolean uncapitalizeNext = true;
331331 for (int i = 0; i < buffer.length; i++) {
332 char ch = buffer[i];
332 final char ch = buffer[i];
333333 if (isDelimiter(ch, delimiters)) {
334334 uncapitalizeNext = true;
335335 } else if (uncapitalizeNext) {
363363 * @param str the String to swap case, may be null
364364 * @return the changed String, <code>null</code> if null String input
365365 */
366 public static String swapCase(String str) {
366 public static String swapCase(final String str) {
367367 if (StringUtils.isEmpty(str)) {
368368 return str;
369369 }
370 char[] buffer = str.toCharArray();
370 final char[] buffer = str.toCharArray();
371371
372372 boolean whitespace = true;
373373
374374 for (int i = 0; i < buffer.length; i++) {
375 char ch = buffer[i];
375 final char ch = buffer[i];
376376 if (Character.isUpperCase(ch)) {
377377 buffer[i] = Character.toLowerCase(ch);
378378 whitespace = false;
416416 * @see #initials(String,char[])
417417 * @since 2.2
418418 */
419 public static String initials(String str) {
419 public static String initials(final String str) {
420420 return initials(str, null);
421421 }
422422
447447 * @see #initials(String)
448448 * @since 2.2
449449 */
450 public static String initials(String str, char... delimiters) {
450 public static String initials(final String str, final char... delimiters) {
451451 if (StringUtils.isEmpty(str)) {
452452 return str;
453453 }
454454 if (delimiters != null && delimiters.length == 0) {
455455 return "";
456456 }
457 int strLen = str.length();
458 char[] buf = new char[strLen / 2 + 1];
457 final int strLen = str.length();
458 final char[] buf = new char[strLen / 2 + 1];
459459 int count = 0;
460460 boolean lastWasGap = true;
461461 for (int i = 0; i < strLen; i++) {
462 char ch = str.charAt(i);
462 final char ch = str.charAt(i);
463463
464464 if (isDelimiter(ch, delimiters)) {
465465 lastWasGap = true;
481481 * @param delimiters the delimiters
482482 * @return true if it is a delimiter
483483 */
484 private static boolean isDelimiter(char ch, char[] delimiters) {
484 private static boolean isDelimiter(final char ch, final char[] delimiters) {
485485 if (delimiters == null) {
486486 return Character.isWhitespace(ch);
487487 }
488 for (char delimiter : delimiters) {
488 for (final char delimiter : delimiters) {
489489 if (ch == delimiter) {
490490 return true;
491491 }
2525 * the first translator consumes codepoints from the input.
2626 *
2727 * @since 3.0
28 * @version $Id: AggregateTranslator.java 1088899 2011-04-05 05:31:27Z bayard $
28 * @version $Id: AggregateTranslator.java 1436770 2013-01-22 07:09:45Z ggregory $
2929 */
3030 public class AggregateTranslator extends CharSequenceTranslator {
3131
3636 *
3737 * @param translators CharSequenceTranslator array to aggregate
3838 */
39 public AggregateTranslator(CharSequenceTranslator... translators) {
39 public AggregateTranslator(final CharSequenceTranslator... translators) {
4040 this.translators = ArrayUtils.clone(translators);
4141 }
4242
4646 * {@inheritDoc}
4747 */
4848 @Override
49 public int translate(CharSequence input, int index, Writer out) throws IOException {
50 for (CharSequenceTranslator translator : translators) {
51 int consumed = translator.translate(input, index, out);
49 public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
50 for (final CharSequenceTranslator translator : translators) {
51 final int consumed = translator.translate(input, index, out);
5252 if(consumed != 0) {
5353 return consumed;
5454 }
2626 * is completely contextual, the API does not present two separate signatures.
2727 *
2828 * @since 3.0
29 * @version $Id: CharSequenceTranslator.java 1146844 2011-07-14 18:49:51Z mbenson $
29 * @version $Id: CharSequenceTranslator.java 1471063 2013-04-23 17:31:21Z sebb $
3030 */
3131 public abstract class CharSequenceTranslator {
3232
3434 * Translate a set of codepoints, represented by an int index into a CharSequence,
3535 * into another set of codepoints. The number of codepoints consumed must be returned,
3636 * and the only IOExceptions thrown must be from interacting with the Writer so that
37 * the top level API may reliable ignore StringWriter IOExceptions.
37 * the top level API may reliably ignore StringWriter IOExceptions.
3838 *
3939 * @param input CharSequence that is being translated
4040 * @param index int representing the current point of translation
4949 * @param input CharSequence to be translated
5050 * @return String output of translation
5151 */
52 public final String translate(CharSequence input) {
52 public final String translate(final CharSequence input) {
5353 if (input == null) {
5454 return null;
5555 }
5656 try {
57 StringWriter writer = new StringWriter(input.length() * 2);
57 final StringWriter writer = new StringWriter(input.length() * 2);
5858 translate(input, writer);
5959 return writer.toString();
60 } catch (IOException ioe) {
60 } catch (final IOException ioe) {
6161 // this should never ever happen while writing to a StringWriter
6262 throw new RuntimeException(ioe);
6363 }
7171 * @param out Writer to translate the text to
7272 * @throws IOException if and only if the Writer produces an IOException
7373 */
74 public final void translate(CharSequence input, Writer out) throws IOException {
74 public final void translate(final CharSequence input, final Writer out) throws IOException {
7575 if (out == null) {
7676 throw new IllegalArgumentException("The Writer must not be null");
7777 }
7979 return;
8080 }
8181 int pos = 0;
82 int len = input.length();
82 final int len = input.length();
8383 while (pos < len) {
84 int consumed = translate(input, pos, out);
84 final int consumed = translate(input, pos, out);
8585 if (consumed == 0) {
86 char[] c = Character.toChars(Character.codePointAt(input, pos));
86 final char[] c = Character.toChars(Character.codePointAt(input, pos));
8787 out.write(c);
8888 pos+= c.length;
8989 continue;
9191 // // contract with translators is that they have to understand codepoints
9292 // // and they just took care of a surrogate pair
9393 for (int pt = 0; pt < consumed; pt++) {
94 pos += Character.charCount(Character.codePointAt(input, pos));
94 pos += Character.charCount(Character.codePointAt(input, pt));
9595 }
9696 }
9797 }
103103 * @param translators CharSequenceTranslator array of translators to merge with this one
104104 * @return CharSequenceTranslator merging this translator with the others
105105 */
106 public final CharSequenceTranslator with(CharSequenceTranslator... translators) {
107 CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
106 public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
107 final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
108108 newArray[0] = this;
109109 System.arraycopy(translators, 0, newArray, 1, translators.length);
110110 return new AggregateTranslator(newArray);
117117 * @param codepoint The codepoint to convert.
118118 * @return An upper case hexadecimal <code>String</code>
119119 */
120 public static String hex(int codepoint) {
120 public static String hex(final int codepoint) {
121121 return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
122122 }
123123
2323 * will replace up to one character at a time.
2424 *
2525 * @since 3.0
26 * @version $Id: CodePointTranslator.java 1139924 2011-06-26 19:32:14Z mbenson $
26 * @version $Id: CodePointTranslator.java 1553931 2013-12-28 21:24:44Z ggregory $
2727 */
2828 public abstract class CodePointTranslator extends CharSequenceTranslator {
2929
3232 * {@inheritDoc}
3333 */
3434 @Override
35 public final int translate(CharSequence input, int index, Writer out) throws IOException {
36 int codepoint = Character.codePointAt(input, index);
37 boolean consumed = translate(codepoint, out);
38 if (consumed) {
39 return 1;
40 } else {
41 return 0;
42 }
35 public final int translate(final CharSequence input, final int index, final Writer out) throws IOException {
36 final int codepoint = Character.codePointAt(input, index);
37 final boolean consumed = translate(codepoint, out);
38 return consumed ? 1 : 0;
4339 }
4440
4541 /**
2121 * All arrays are of length [*][2].
2222 *
2323 * @since 3.0
24 * @version $Id: EntityArrays.java 1088899 2011-04-05 05:31:27Z bayard $
24 * @version $Id: EntityArrays.java 1436770 2013-01-22 07:09:45Z ggregory $
2525 */
2626 public class EntityArrays {
2727
412412 * @param array String[][] to be inverted
413413 * @return String[][] inverted array
414414 */
415 public static String[][] invert(String[][] array) {
416 String[][] newarray = new String[array.length][2];
415 public static String[][] invert(final String[][] array) {
416 final String[][] newarray = new String[array.length][2];
417417 for(int i = 0; i<array.length; i++) {
418418 newarray[i][0] = array[i][1];
419419 newarray[i][1] = array[i][0];
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.text.translate;
17
18 /**
19 * Translates codepoints to their Unicode escaped value suitable for Java source.
20 *
21 * @since 3.2
22 * @version $Id: JavaUnicodeEscaper.java 1451550 2013-03-01 10:06:13Z olamy $
23 */
24 public class JavaUnicodeEscaper extends UnicodeEscaper {
25
26 /**
27 * <p>
28 * Constructs a <code>JavaUnicodeEscaper</code> above the specified value (exclusive).
29 * </p>
30 *
31 * @param codepoint
32 * above which to escape
33 * @return the newly created {@code UnicodeEscaper} instance
34 */
35 public static JavaUnicodeEscaper above(final int codepoint) {
36 return outsideOf(0, codepoint);
37 }
38
39 /**
40 * <p>
41 * Constructs a <code>JavaUnicodeEscaper</code> below the specified value (exclusive).
42 * </p>
43 *
44 * @param codepoint
45 * below which to escape
46 * @return the newly created {@code UnicodeEscaper} instance
47 */
48 public static JavaUnicodeEscaper below(final int codepoint) {
49 return outsideOf(codepoint, Integer.MAX_VALUE);
50 }
51
52 /**
53 * <p>
54 * Constructs a <code>JavaUnicodeEscaper</code> between the specified values (inclusive).
55 * </p>
56 *
57 * @param codepointLow
58 * above which to escape
59 * @param codepointHigh
60 * below which to escape
61 * @return the newly created {@code UnicodeEscaper} instance
62 */
63 public static JavaUnicodeEscaper between(final int codepointLow, final int codepointHigh) {
64 return new JavaUnicodeEscaper(codepointLow, codepointHigh, true);
65 }
66
67 /**
68 * <p>
69 * Constructs a <code>JavaUnicodeEscaper</code> outside of the specified values (exclusive).
70 * </p>
71 *
72 * @param codepointLow
73 * below which to escape
74 * @param codepointHigh
75 * above which to escape
76 * @return the newly created {@code UnicodeEscaper} instance
77 */
78 public static JavaUnicodeEscaper outsideOf(final int codepointLow, final int codepointHigh) {
79 return new JavaUnicodeEscaper(codepointLow, codepointHigh, false);
80 }
81
82 /**
83 * <p>
84 * Constructs a <code>JavaUnicodeEscaper</code> for the specified range. This is the underlying method for the
85 * other constructors/builders. The <code>below</code> and <code>above</code> boundaries are inclusive when
86 * <code>between</code> is <code>true</code> and exclusive when it is <code>false</code>.
87 * </p>
88 *
89 * @param below
90 * int value representing the lowest codepoint boundary
91 * @param above
92 * int value representing the highest codepoint boundary
93 * @param between
94 * whether to escape between the boundaries or outside them
95 */
96 public JavaUnicodeEscaper(final int below, final int above, final boolean between) {
97 super(below, above, between);
98 }
99
100 /**
101 * Converts the given codepoint to a hex string of the form {@code "\\uXXXX\\uXXXX"}
102 *
103 * @param codepoint
104 * a Unicode code point
105 * @return the hex string for the given codepoint
106 */
107 @Override
108 protected String toUtf16Escape(final int codepoint) {
109 final char[] surrogatePair = Character.toChars(codepoint);
110 return "\\u" + hex(surrogatePair[0]) + "\\u" + hex(surrogatePair[1]);
111 }
112
113 }
2121
2222 /**
2323 * Translates a value using a lookup table.
24 *
24 *
2525 * @since 3.0
26 * @version $Id: LookupTranslator.java 1091096 2011-04-11 15:07:29Z mbenson $
26 * @version $Id: LookupTranslator.java 1470822 2013-04-23 06:00:41Z bayard $
2727 */
2828 public class LookupTranslator extends CharSequenceTranslator {
2929
30 private final HashMap<CharSequence, CharSequence> lookupMap;
30 private final HashMap<String, CharSequence> lookupMap;
3131 private final int shortest;
3232 private final int longest;
3333
3434 /**
3535 * Define the lookup table to be used in translation
3636 *
37 * Note that, as of Lang 3.1, the key to the lookup table is converted to a
38 * java.lang.String, while the value remains as a java.lang.CharSequence.
39 * This is because we need the key to support hashCode and equals(Object),
40 * allowing it to be the key for a HashMap. See LANG-882.
41 *
3742 * @param lookup CharSequence[][] table of size [*][2]
3843 */
39 public LookupTranslator(CharSequence[]... lookup) {
40 lookupMap = new HashMap<CharSequence, CharSequence>();
44 public LookupTranslator(final CharSequence[]... lookup) {
45 lookupMap = new HashMap<String, CharSequence>();
4146 int _shortest = Integer.MAX_VALUE;
4247 int _longest = 0;
4348 if (lookup != null) {
44 for (CharSequence[] seq : lookup) {
45 this.lookupMap.put(seq[0], seq[1]);
46 int sz = seq[0].length();
49 for (final CharSequence[] seq : lookup) {
50 this.lookupMap.put(seq[0].toString(), seq[1]);
51 final int sz = seq[0].length();
4752 if (sz < _shortest) {
4853 _shortest = sz;
4954 }
6065 * {@inheritDoc}
6166 */
6267 @Override
63 public int translate(CharSequence input, int index, Writer out) throws IOException {
68 public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
6469 int max = longest;
6570 if (index + longest > input.length()) {
6671 max = input.length() - index;
6772 }
6873 // descend so as to get a greedy algorithm
6974 for (int i = max; i >= shortest; i--) {
70 CharSequence subSeq = input.subSequence(index, index + i);
71 CharSequence result = lookupMap.get(subSeq);
75 final CharSequence subSeq = input.subSequence(index, index + i);
76 final CharSequence result = lookupMap.get(subSeq.toString());
7277 if (result != null) {
7378 out.write(result.toString());
7479 return i;
2222 * Translates codepoints to their XML numeric entity escaped value.
2323 *
2424 * @since 3.0
25 * @version $Id: NumericEntityEscaper.java 1142151 2011-07-02 04:06:23Z bayard $
25 * @version $Id: NumericEntityEscaper.java 1436768 2013-01-22 07:07:42Z ggregory $
2626 */
2727 public class NumericEntityEscaper extends CodePointTranslator {
2828
4040 * @param above int value representing the highest codepoint boundary
4141 * @param between whether to escape between the boundaries or outside them
4242 */
43 private NumericEntityEscaper(int below, int above, boolean between) {
43 private NumericEntityEscaper(final int below, final int above, final boolean between) {
4444 this.below = below;
4545 this.above = above;
4646 this.between = between;
5959 * @param codepoint below which to escape
6060 * @return the newly created {@code NumericEntityEscaper} instance
6161 */
62 public static NumericEntityEscaper below(int codepoint) {
62 public static NumericEntityEscaper below(final int codepoint) {
6363 return outsideOf(codepoint, Integer.MAX_VALUE);
6464 }
6565
6969 * @param codepoint above which to escape
7070 * @return the newly created {@code NumericEntityEscaper} instance
7171 */
72 public static NumericEntityEscaper above(int codepoint) {
72 public static NumericEntityEscaper above(final int codepoint) {
7373 return outsideOf(0, codepoint);
7474 }
7575
8080 * @param codepointHigh below which to escape
8181 * @return the newly created {@code NumericEntityEscaper} instance
8282 */
83 public static NumericEntityEscaper between(int codepointLow, int codepointHigh) {
83 public static NumericEntityEscaper between(final int codepointLow, final int codepointHigh) {
8484 return new NumericEntityEscaper(codepointLow, codepointHigh, true);
8585 }
8686
9191 * @param codepointHigh above which to escape
9292 * @return the newly created {@code NumericEntityEscaper} instance
9393 */
94 public static NumericEntityEscaper outsideOf(int codepointLow, int codepointHigh) {
94 public static NumericEntityEscaper outsideOf(final int codepointLow, final int codepointHigh) {
9595 return new NumericEntityEscaper(codepointLow, codepointHigh, false);
9696 }
9797
9999 * {@inheritDoc}
100100 */
101101 @Override
102 public boolean translate(int codepoint, Writer out) throws IOException {
102 public boolean translate(final int codepoint, final Writer out) throws IOException {
103103 if(between) {
104104 if (codepoint < below || codepoint > above) {
105105 return false;
2727 * Note that the semi-colon is optional.
2828 *
2929 * @since 3.0
30 * @version $Id: NumericEntityUnescaper.java 1199894 2011-11-09 17:53:59Z ggregory $
30 * @version $Id: NumericEntityUnescaper.java 1436770 2013-01-22 07:09:45Z ggregory $
3131 */
3232 public class NumericEntityUnescaper extends CharSequenceTranslator {
3333
5252 *
5353 * @param options to apply to this unescaper
5454 */
55 public NumericEntityUnescaper(OPTION... options) {
55 public NumericEntityUnescaper(final OPTION... options) {
5656 if(options.length > 0) {
5757 this.options = EnumSet.copyOf(Arrays.asList(options));
5858 } else {
6666 * @param option to check state of
6767 * @return whether the option is set
6868 */
69 public boolean isSet(OPTION option) {
69 public boolean isSet(final OPTION option) {
7070 return options == null ? false : options.contains(option);
7171 }
7272
7474 * {@inheritDoc}
7575 */
7676 @Override
77 public int translate(CharSequence input, int index, Writer out) throws IOException {
78 int seqEnd = input.length();
77 public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
78 final int seqEnd = input.length();
7979 // Uses -2 to ensure there is something after the &#
8080 if(input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
8181 int start = index + 2;
8282 boolean isHex = false;
8383
84 char firstChar = input.charAt(start);
84 final char firstChar = input.charAt(start);
8585 if(firstChar == 'x' || firstChar == 'X') {
8686 start++;
8787 isHex = true;
101101 end++;
102102 }
103103
104 boolean semiNext = end != seqEnd && input.charAt(end) == ';';
104 final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
105105
106106 if(!semiNext) {
107107 if(isSet(OPTION.semiColonRequired)) {
119119 } else {
120120 entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
121121 }
122 } catch(NumberFormatException nfe) {
122 } catch(final NumberFormatException nfe) {
123123 return 0;
124124 }
125125
126126 if(entityValue > 0xFFFF) {
127 char[] chrs = Character.toChars(entityValue);
127 final char[] chrs = Character.toChars(entityValue);
128128 out.write(chrs[0]);
129129 out.write(chrs[1]);
130130 } else {
2424 * For example, "\45" should go back to being the specific value (a %).
2525 *
2626 * Note that this currently only supports the viable range of octal for Java; namely
27 * 1 to 377. This is both because parsing Java is the main use case and Integer.parseInt
28 * throws an exception when values are larger than octal 377.
27 * 1 to 377. This is because parsing Java is the main use case.
2928 *
3029 * @since 3.0
3130 * @version $Id: OctalUnescaper.java 967237 2010-07-23 20:08:57Z mbenson $
3231 */
3332 public class OctalUnescaper extends CharSequenceTranslator {
3433
35 private static int OCTAL_MAX = 377;
36
3734 /**
3835 * {@inheritDoc}
3936 */
4037 @Override
41 public int translate(CharSequence input, int index, Writer out) throws IOException {
42 if(input.charAt(index) == '\\' && index < (input.length() - 1) && Character.isDigit(input.charAt(index + 1)) ) {
43 int start = index + 1;
38 public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
39 int remaining = input.length() - index - 1; // how many characters left, ignoring the first \
40 StringBuilder builder = new StringBuilder();
41 if(input.charAt(index) == '\\' && remaining > 0 && isOctalDigit(input.charAt(index + 1)) ) {
42 int next = index + 1;
43 int next2 = index + 2;
44 int next3 = index + 3;
4445
45 int end = index + 2;
46 while ( end < input.length() && Character.isDigit(input.charAt(end)) ) {
47 end++;
48 if ( Integer.parseInt(input.subSequence(start, end).toString(), 10) > OCTAL_MAX) {
49 end--; // rollback
50 break;
46 // we know this is good as we checked it in the if block above
47 builder.append(input.charAt(next));
48
49 if(remaining > 1 && isOctalDigit(input.charAt(next2))) {
50 builder.append(input.charAt(next2));
51 if(remaining > 2 && isZeroToThree(input.charAt(next)) && isOctalDigit(input.charAt(next3))) {
52 builder.append(input.charAt(next3));
5153 }
5254 }
5355
54 out.write( Integer.parseInt(input.subSequence(start, end).toString(), 8) );
55 return 1 + end - start;
56 out.write( Integer.parseInt(builder.toString(), 8) );
57 return 1 + builder.length();
5658 }
5759 return 0;
5860 }
61
62 /**
63 * Checks if the given char is an octal digit. Octal digits are the character representations of the digits 0 to 7.
64 * @param ch the char to check
65 * @return true if the given char is the character representation of one of the digits from 0 to 7
66 */
67 private boolean isOctalDigit(char ch) {
68 return ch >= '0' && ch <= '7';
69 }
70
71 /**
72 * Checks if the given char is the character representation of one of the digit from 0 to 3.
73 * @param ch the char to check
74 * @return true if the given char is the character representation of one of the digits from 0 to 3
75 */
76 private boolean isZeroToThree(char ch) {
77 return ch >= '0' && ch <= '3';
78 }
5979 }
2222 * Translates codepoints to their Unicode escaped value.
2323 *
2424 * @since 3.0
25 * @version $Id: UnicodeEscaper.java 1148520 2011-07-19 20:53:23Z ggregory $
25 * @version $Id: UnicodeEscaper.java 1552652 2013-12-20 13:23:16Z britter $
2626 */
2727 public class UnicodeEscaper extends CodePointTranslator {
2828
4747 * @param above int value representing the highest codepoint boundary
4848 * @param between whether to escape between the boundaries or outside them
4949 */
50 private UnicodeEscaper(int below, int above, boolean between) {
50 protected UnicodeEscaper(final int below, final int above, final boolean between) {
5151 this.below = below;
5252 this.above = above;
5353 this.between = between;
5959 * @param codepoint below which to escape
6060 * @return the newly created {@code UnicodeEscaper} instance
6161 */
62 public static UnicodeEscaper below(int codepoint) {
62 public static UnicodeEscaper below(final int codepoint) {
6363 return outsideOf(codepoint, Integer.MAX_VALUE);
6464 }
6565
6969 * @param codepoint above which to escape
7070 * @return the newly created {@code UnicodeEscaper} instance
7171 */
72 public static UnicodeEscaper above(int codepoint) {
72 public static UnicodeEscaper above(final int codepoint) {
7373 return outsideOf(0, codepoint);
7474 }
7575
8080 * @param codepointHigh above which to escape
8181 * @return the newly created {@code UnicodeEscaper} instance
8282 */
83 public static UnicodeEscaper outsideOf(int codepointLow, int codepointHigh) {
83 public static UnicodeEscaper outsideOf(final int codepointLow, final int codepointHigh) {
8484 return new UnicodeEscaper(codepointLow, codepointHigh, false);
8585 }
8686
9191 * @param codepointHigh below which to escape
9292 * @return the newly created {@code UnicodeEscaper} instance
9393 */
94 public static UnicodeEscaper between(int codepointLow, int codepointHigh) {
94 public static UnicodeEscaper between(final int codepointLow, final int codepointHigh) {
9595 return new UnicodeEscaper(codepointLow, codepointHigh, true);
9696 }
9797
9999 * {@inheritDoc}
100100 */
101101 @Override
102 public boolean translate(int codepoint, Writer out) throws IOException {
103 if(between) {
102 public boolean translate(final int codepoint, final Writer out) throws IOException {
103 if (between) {
104104 if (codepoint < below || codepoint > above) {
105105 return false;
106106 }
112112
113113 // TODO: Handle potential + sign per various Unicode escape implementations
114114 if (codepoint > 0xffff) {
115 // TODO: Figure out what to do. Output as two Unicodes?
116 // Does this make this a Java-specific output class?
117 out.write("\\u" + hex(codepoint));
115 out.write(toUtf16Escape(codepoint));
118116 } else if (codepoint > 0xfff) {
119117 out.write("\\u" + hex(codepoint));
120118 } else if (codepoint > 0xff) {
126124 }
127125 return true;
128126 }
127
128 /**
129 * Converts the given codepoint to a hex string of the form {@code "\\uXXXX"}
130 *
131 * @param codepoint
132 * a Unicode code point
133 * @return the hex string for the given codepoint
134 *
135 * @since 3.2
136 */
137 protected String toUtf16Escape(final int codepoint) {
138 return "\\u" + hex(codepoint);
139 }
129140 }
2424 * without the +.
2525 *
2626 * @since 3.0
27 * @version $Id: UnicodeUnescaper.java 1199894 2011-11-09 17:53:59Z ggregory $
27 * @version $Id: UnicodeUnescaper.java 1436770 2013-01-22 07:09:45Z ggregory $
2828 */
2929 public class UnicodeUnescaper extends CharSequenceTranslator {
3030
3232 * {@inheritDoc}
3333 */
3434 @Override
35 public int translate(CharSequence input, int index, Writer out) throws IOException {
35 public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
3636 if (input.charAt(index) == '\\' && index + 1 < input.length() && input.charAt(index + 1) == 'u') {
3737 // consume optional additional 'u' chars
3838 int i = 2;
4646
4747 if (index + i + 4 <= input.length()) {
4848 // Get 4 hex digits
49 CharSequence unicode = input.subSequence(index + i, index + i + 4);
49 final CharSequence unicode = input.subSequence(index + i, index + i + 4);
5050
5151 try {
52 int value = Integer.parseInt(unicode.toString(), 16);
52 final int value = Integer.parseInt(unicode.toString(), 16);
5353 out.write((char) value);
54 } catch (NumberFormatException nfe) {
54 } catch (final NumberFormatException nfe) {
5555 throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe);
5656 }
5757 return i + 4;
2626 * <p>Formatting is performed using the thread-safe
2727 * {@link org.apache.commons.lang3.time.FastDateFormat} class.</p>
2828 *
29 * <p>Note that the JDK has a bug wherein calling Calendar.get(int) will
30 * override any previously called Calendar.clear() calls. See LANG-755.</p>
31 *
2932 * @since 2.0
30 * @version $Id: DateFormatUtils.java 1088899 2011-04-05 05:31:27Z bayard $
33 * @version $Id: DateFormatUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
3134 */
3235 public class DateFormatUtils {
3336
123126 * @param pattern the pattern to use to format the date, not null
124127 * @return the formatted date
125128 */
126 public static String formatUTC(long millis, String pattern) {
129 public static String formatUTC(final long millis, final String pattern) {
127130 return format(new Date(millis), pattern, UTC_TIME_ZONE, null);
128131 }
129132
134137 * @param pattern the pattern to use to format the date, not null
135138 * @return the formatted date
136139 */
137 public static String formatUTC(Date date, String pattern) {
140 public static String formatUTC(final Date date, final String pattern) {
138141 return format(date, pattern, UTC_TIME_ZONE, null);
139142 }
140143
146149 * @param locale the locale to use, may be <code>null</code>
147150 * @return the formatted date
148151 */
149 public static String formatUTC(long millis, String pattern, Locale locale) {
152 public static String formatUTC(final long millis, final String pattern, final Locale locale) {
150153 return format(new Date(millis), pattern, UTC_TIME_ZONE, locale);
151154 }
152155
158161 * @param locale the locale to use, may be <code>null</code>
159162 * @return the formatted date
160163 */
161 public static String formatUTC(Date date, String pattern, Locale locale) {
164 public static String formatUTC(final Date date, final String pattern, final Locale locale) {
162165 return format(date, pattern, UTC_TIME_ZONE, locale);
163166 }
164167
169172 * @param pattern the pattern to use to format the date, not null
170173 * @return the formatted date
171174 */
172 public static String format(long millis, String pattern) {
175 public static String format(final long millis, final String pattern) {
173176 return format(new Date(millis), pattern, null, null);
174177 }
175178
180183 * @param pattern the pattern to use to format the date, not null
181184 * @return the formatted date
182185 */
183 public static String format(Date date, String pattern) {
186 public static String format(final Date date, final String pattern) {
184187 return format(date, pattern, null, null);
185188 }
186189
193196 * @see FastDateFormat#format(Calendar)
194197 * @since 2.4
195198 */
196 public static String format(Calendar calendar, String pattern) {
199 public static String format(final Calendar calendar, final String pattern) {
197200 return format(calendar, pattern, null, null);
198201 }
199202
205208 * @param timeZone the time zone to use, may be <code>null</code>
206209 * @return the formatted date
207210 */
208 public static String format(long millis, String pattern, TimeZone timeZone) {
211 public static String format(final long millis, final String pattern, final TimeZone timeZone) {
209212 return format(new Date(millis), pattern, timeZone, null);
210213 }
211214
217220 * @param timeZone the time zone to use, may be <code>null</code>
218221 * @return the formatted date
219222 */
220 public static String format(Date date, String pattern, TimeZone timeZone) {
223 public static String format(final Date date, final String pattern, final TimeZone timeZone) {
221224 return format(date, pattern, timeZone, null);
222225 }
223226
231234 * @see FastDateFormat#format(Calendar)
232235 * @since 2.4
233236 */
234 public static String format(Calendar calendar, String pattern, TimeZone timeZone) {
237 public static String format(final Calendar calendar, final String pattern, final TimeZone timeZone) {
235238 return format(calendar, pattern, timeZone, null);
236239 }
237240
243246 * @param locale the locale to use, may be <code>null</code>
244247 * @return the formatted date
245248 */
246 public static String format(long millis, String pattern, Locale locale) {
249 public static String format(final long millis, final String pattern, final Locale locale) {
247250 return format(new Date(millis), pattern, null, locale);
248251 }
249252
255258 * @param locale the locale to use, may be <code>null</code>
256259 * @return the formatted date
257260 */
258 public static String format(Date date, String pattern, Locale locale) {
261 public static String format(final Date date, final String pattern, final Locale locale) {
259262 return format(date, pattern, null, locale);
260263 }
261264
269272 * @see FastDateFormat#format(Calendar)
270273 * @since 2.4
271274 */
272 public static String format(Calendar calendar, String pattern, Locale locale) {
275 public static String format(final Calendar calendar, final String pattern, final Locale locale) {
273276 return format(calendar, pattern, null, locale);
274277 }
275278
282285 * @param locale the locale to use, may be <code>null</code>
283286 * @return the formatted date
284287 */
285 public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) {
288 public static String format(final long millis, final String pattern, final TimeZone timeZone, final Locale locale) {
286289 return format(new Date(millis), pattern, timeZone, locale);
287290 }
288291
295298 * @param locale the locale to use, may be <code>null</code>
296299 * @return the formatted date
297300 */
298 public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) {
299 FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
301 public static String format(final Date date, final String pattern, final TimeZone timeZone, final Locale locale) {
302 final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
300303 return df.format(date);
301304 }
302305
311314 * @see FastDateFormat#format(Calendar)
312315 * @since 2.4
313316 */
314 public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) {
315 FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
317 public static String format(final Calendar calendar, final String pattern, final TimeZone timeZone, final Locale locale) {
318 final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
316319 return df.format(calendar);
317320 }
318321
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import java.text.ParseException;
19 import java.text.ParsePosition;
20 import java.util.Date;
21 import java.util.Locale;
22 import java.util.TimeZone;
23
24 /**
25 * <p>DateParser is the "missing" interface for the parsing methods of
26 * {@link java.text.DateFormat}.</p>
27 *
28 * @since 3.2
29 */
30 public interface DateParser {
31
32 /**
33 * Equivalent to DateFormat.parse(String).
34 *
35 * See {@link java.text.DateFormat#parse(String)} for more information.
36 * @param source A <code>String</code> whose beginning should be parsed.
37 * @return A <code>Date</code> parsed from the string
38 * @throws ParseException if the beginning of the specified string cannot be parsed.
39 */
40 Date parse(String source) throws ParseException;
41
42 /**
43 * Equivalent to DateFormat.parse(String, ParsePosition).
44 *
45 * See {@link java.text.DateFormat#parse(String, ParsePosition)} for more information.
46 *
47 * @param source A <code>String</code>, part of which should be parsed.
48 * @param pos A <code>ParsePosition</code> object with index and error index information
49 * as described above.
50 * @return A <code>Date</code> parsed from the string. In case of error, returns null.
51 * @throws NullPointerException if text or pos is null.
52 */
53 Date parse(String source, ParsePosition pos);
54
55 // Accessors
56 //-----------------------------------------------------------------------
57 /**
58 * <p>Get the pattern used by this parser.</p>
59 *
60 * @return the pattern, {@link java.text.SimpleDateFormat} compatible
61 */
62 String getPattern();
63
64 /**
65 * <p>
66 * Get the time zone used by this parser.
67 * </p>
68 *
69 * <p>
70 * The default {@link TimeZone} used to create a {@link Date} when the {@link TimeZone} is not specified by
71 * the format pattern.
72 * </p>
73 *
74 * @return the time zone
75 */
76 TimeZone getTimeZone();
77
78 /**
79 * <p>Get the locale used by this parser.</p>
80 *
81 * @return the locale
82 */
83 Locale getLocale();
84
85 /**
86 * Parses text from a string to produce a Date.
87 *
88 * @param source A <code>String</code> whose beginning should be parsed.
89 * @return a <code>java.util.Date</code> object
90 * @throws ParseException if the beginning of the specified string cannot be parsed.
91 * @see java.text.DateFormat#parseObject(String)
92 */
93 Object parseObject(String source) throws ParseException;
94
95 /**
96 * Parse a date/time string according to the given parse position.
97 *
98 * @param source A <code>String</code> whose beginning should be parsed.
99 * @param pos the parse position
100 * @return a <code>java.util.Date</code> object
101 * @see java.text.DateFormat#parseObject(String, ParsePosition)
102 */
103 Object parseObject(String source, ParsePosition pos);
104 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import java.text.FieldPosition;
19 import java.util.Calendar;
20 import java.util.Date;
21 import java.util.Locale;
22 import java.util.TimeZone;
23
24 /**
25 * <p>DatePrinter is the "missing" interface for the format methods of
26 * {@link java.text.DateFormat}.</p>
27 *
28 * @since 3.2
29 */
30 public interface DatePrinter {
31
32 /**
33 * <p>Formats a millisecond {@code long} value.</p>
34 *
35 * @param millis the millisecond value to format
36 * @return the formatted string
37 * @since 2.1
38 */
39 String format(long millis);
40
41 /**
42 * <p>Formats a {@code Date} object using a {@code GregorianCalendar}.</p>
43 *
44 * @param date the date to format
45 * @return the formatted string
46 */
47 String format(Date date);
48
49 /**
50 * <p>Formats a {@code Calendar} object.</p>
51 *
52 * @param calendar the calendar to format
53 * @return the formatted string
54 */
55 String format(Calendar calendar);
56
57 /**
58 * <p>Formats a milliseond {@code long} value into the
59 * supplied {@code StringBuffer}.</p>
60 *
61 * @param millis the millisecond value to format
62 * @param buf the buffer to format into
63 * @return the specified string buffer
64 */
65 StringBuffer format(long millis, StringBuffer buf);
66
67 /**
68 * <p>Formats a {@code Date} object into the
69 * supplied {@code StringBuffer} using a {@code GregorianCalendar}.</p>
70 *
71 * @param date the date to format
72 * @param buf the buffer to format into
73 * @return the specified string buffer
74 */
75 StringBuffer format(Date date, StringBuffer buf);
76
77 /**
78 * <p>Formats a {@code Calendar} object into the
79 * supplied {@code StringBuffer}.</p>
80 *
81 * @param calendar the calendar to format
82 * @param buf the buffer to format into
83 * @return the specified string buffer
84 */
85 StringBuffer format(Calendar calendar, StringBuffer buf);
86
87 // Accessors
88 //-----------------------------------------------------------------------
89 /**
90 * <p>Gets the pattern used by this printer.</p>
91 *
92 * @return the pattern, {@link java.text.SimpleDateFormat} compatible
93 */
94 String getPattern();
95
96 /**
97 * <p>Gets the time zone used by this printer.</p>
98 *
99 * <p>This zone is always used for {@code Date} printing. </p>
100 *
101 * @return the time zone
102 */
103 TimeZone getTimeZone();
104
105 /**
106 * <p>Gets the locale used by this printer.</p>
107 *
108 * @return the locale
109 */
110 Locale getLocale();
111
112 /**
113 * <p>Formats a {@code Date}, {@code Calendar} or
114 * {@code Long} (milliseconds) object.</p>
115 *
116 * See {@link java.text.DateFormat#format(Object, StringBuffer, FieldPosition)}
117 *
118 * @param obj the object to format
119 * @param toAppendTo the buffer to append to
120 * @param pos the position - ignored
121 * @return the buffer passed in
122 */
123 StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos);
124 }
2121 import java.util.Calendar;
2222 import java.util.Date;
2323 import java.util.Iterator;
24 import java.util.Locale;
2425 import java.util.NoSuchElementException;
2526
2627 /**
3940 * </p>
4041 *
4142 * @since 2.0
42 * @version $Id: DateUtils.java 1144992 2011-07-11 00:49:04Z ggregory $
43 * @version $Id: DateUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
4344 */
4445 public class DateUtils {
4546
149150 * @throws IllegalArgumentException if either date is <code>null</code>
150151 * @since 2.1
151152 */
152 public static boolean isSameDay(Date date1, Date date2) {
153 public static boolean isSameDay(final Date date1, final Date date2) {
153154 if (date1 == null || date2 == null) {
154155 throw new IllegalArgumentException("The date must not be null");
155156 }
156 Calendar cal1 = Calendar.getInstance();
157 final Calendar cal1 = Calendar.getInstance();
157158 cal1.setTime(date1);
158 Calendar cal2 = Calendar.getInstance();
159 final Calendar cal2 = Calendar.getInstance();
159160 cal2.setTime(date2);
160161 return isSameDay(cal1, cal2);
161162 }
173174 * @throws IllegalArgumentException if either calendar is <code>null</code>
174175 * @since 2.1
175176 */
176 public static boolean isSameDay(Calendar cal1, Calendar cal2) {
177 public static boolean isSameDay(final Calendar cal1, final Calendar cal2) {
177178 if (cal1 == null || cal2 == null) {
178179 throw new IllegalArgumentException("The date must not be null");
179180 }
194195 * @throws IllegalArgumentException if either date is <code>null</code>
195196 * @since 2.1
196197 */
197 public static boolean isSameInstant(Date date1, Date date2) {
198 public static boolean isSameInstant(final Date date1, final Date date2) {
198199 if (date1 == null || date2 == null) {
199200 throw new IllegalArgumentException("The date must not be null");
200201 }
212213 * @throws IllegalArgumentException if either date is <code>null</code>
213214 * @since 2.1
214215 */
215 public static boolean isSameInstant(Calendar cal1, Calendar cal2) {
216 public static boolean isSameInstant(final Calendar cal1, final Calendar cal2) {
216217 if (cal1 == null || cal2 == null) {
217218 throw new IllegalArgumentException("The date must not be null");
218219 }
232233 * @throws IllegalArgumentException if either date is <code>null</code>
233234 * @since 2.1
234235 */
235 public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
236 public static boolean isSameLocalTime(final Calendar cal1, final Calendar cal2) {
236237 if (cal1 == null || cal2 == null) {
237238 throw new IllegalArgumentException("The date must not be null");
238239 }
261262 * @throws IllegalArgumentException if the date string or pattern array is null
262263 * @throws ParseException if none of the date patterns were suitable (or there were none)
263264 */
264 public static Date parseDate(String str, String... parsePatterns) throws ParseException {
265 return parseDateWithLeniency(str, parsePatterns, true);
265 public static Date parseDate(final String str, final String... parsePatterns) throws ParseException {
266 return parseDate(str, null, parsePatterns);
266267 }
267268
269 //-----------------------------------------------------------------------
270 /**
271 * <p>Parses a string representing a date by trying a variety of different parsers,
272 * using the default date format symbols for the given locale.</p>
273 *
274 * <p>The parse will try each parse pattern in turn.
275 * A parse is only deemed successful if it parses the whole of the input string.
276 * If no parse patterns match, a ParseException is thrown.</p>
277 * The parser will be lenient toward the parsed date.
278 *
279 * @param str the date to parse, not null
280 * @param locale the locale whose date format symbols should be used. If <code>null</code>,
281 * the system locale is used (as per {@link #parseDate(String, String...)}).
282 * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null
283 * @return the parsed date
284 * @throws IllegalArgumentException if the date string or pattern array is null
285 * @throws ParseException if none of the date patterns were suitable (or there were none)
286 * @since 3.2
287 */
288 public static Date parseDate(final String str, final Locale locale, final String... parsePatterns) throws ParseException {
289 return parseDateWithLeniency(str, locale, parsePatterns, true);
290 }
291
268292 //-----------------------------------------------------------------------
269293 /**
270294 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
281305 * @throws ParseException if none of the date patterns were suitable
282306 * @since 2.5
283307 */
284 public static Date parseDateStrictly(String str, String... parsePatterns) throws ParseException {
285 return parseDateWithLeniency(str, parsePatterns, false);
286 }
287
288 /**
289 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
308 public static Date parseDateStrictly(final String str, final String... parsePatterns) throws ParseException {
309 return parseDateStrictly(str, null, parsePatterns);
310 }
311
312 /**
313 * <p>Parses a string representing a date by trying a variety of different parsers,
314 * using the default date format symbols for the given locale..</p>
290315 *
291316 * <p>The parse will try each parse pattern in turn.
292317 * A parse is only deemed successful if it parses the whole of the input string.
293318 * If no parse patterns match, a ParseException is thrown.</p>
319 * The parser parses strictly - it does not allow for dates such as "February 942, 1996".
294320 *
295321 * @param str the date to parse, not null
322 * @param locale the locale whose date format symbols should be used. If <code>null</code>,
323 * the system locale is used (as per {@link #parseDateStrictly(String, String...)}).
324 * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null
325 * @return the parsed date
326 * @throws IllegalArgumentException if the date string or pattern array is null
327 * @throws ParseException if none of the date patterns were suitable
328 * @since 3.2
329 */
330 public static Date parseDateStrictly(final String str, final Locale locale, final String... parsePatterns) throws ParseException {
331 return parseDateWithLeniency(str, null, parsePatterns, false);
332 }
333
334 /**
335 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
336 *
337 * <p>The parse will try each parse pattern in turn.
338 * A parse is only deemed successful if it parses the whole of the input string.
339 * If no parse patterns match, a ParseException is thrown.</p>
340 *
341 * @param str the date to parse, not null
342 * @param locale the locale to use when interpretting the pattern, can be null in which
343 * case the default system locale is used
296344 * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null
297345 * @param lenient Specify whether or not date/time parsing is to be lenient.
298346 * @return the parsed date
301349 * @see java.util.Calender#isLenient()
302350 */
303351 private static Date parseDateWithLeniency(
304 String str, String[] parsePatterns, boolean lenient) throws ParseException {
352 final String str, final Locale locale, final String[] parsePatterns, final boolean lenient) throws ParseException {
305353 if (str == null || parsePatterns == null) {
306354 throw new IllegalArgumentException("Date and Patterns must not be null");
307355 }
308356
309 SimpleDateFormat parser = new SimpleDateFormat();
357 SimpleDateFormat parser;
358 if (locale == null) {
359 parser = new SimpleDateFormat();
360 } else {
361 parser = new SimpleDateFormat("", locale);
362 }
363
310364 parser.setLenient(lenient);
311 ParsePosition pos = new ParsePosition(0);
312 for (String parsePattern : parsePatterns) {
365 final ParsePosition pos = new ParsePosition(0);
366 for (final String parsePattern : parsePatterns) {
313367
314368 String pattern = parsePattern;
315369
327381 str2 = str.replaceAll("([-+][0-9][0-9]):([0-9][0-9])$", "$1$2");
328382 }
329383
330 Date date = parser.parse(str2, pos);
384 final Date date = parser.parse(str2, pos);
331385 if (date != null && pos.getIndex() == str2.length()) {
332386 return date;
333387 }
345399 * @return the new {@code Date} with the amount added
346400 * @throws IllegalArgumentException if the date is null
347401 */
348 public static Date addYears(Date date, int amount) {
402 public static Date addYears(final Date date, final int amount) {
349403 return add(date, Calendar.YEAR, amount);
350404 }
351405
359413 * @return the new {@code Date} with the amount added
360414 * @throws IllegalArgumentException if the date is null
361415 */
362 public static Date addMonths(Date date, int amount) {
416 public static Date addMonths(final Date date, final int amount) {
363417 return add(date, Calendar.MONTH, amount);
364418 }
365419
373427 * @return the new {@code Date} with the amount added
374428 * @throws IllegalArgumentException if the date is null
375429 */
376 public static Date addWeeks(Date date, int amount) {
430 public static Date addWeeks(final Date date, final int amount) {
377431 return add(date, Calendar.WEEK_OF_YEAR, amount);
378432 }
379433
387441 * @return the new {@code Date} with the amount added
388442 * @throws IllegalArgumentException if the date is null
389443 */
390 public static Date addDays(Date date, int amount) {
444 public static Date addDays(final Date date, final int amount) {
391445 return add(date, Calendar.DAY_OF_MONTH, amount);
392446 }
393447
401455 * @return the new {@code Date} with the amount added
402456 * @throws IllegalArgumentException if the date is null
403457 */
404 public static Date addHours(Date date, int amount) {
458 public static Date addHours(final Date date, final int amount) {
405459 return add(date, Calendar.HOUR_OF_DAY, amount);
406460 }
407461
415469 * @return the new {@code Date} with the amount added
416470 * @throws IllegalArgumentException if the date is null
417471 */
418 public static Date addMinutes(Date date, int amount) {
472 public static Date addMinutes(final Date date, final int amount) {
419473 return add(date, Calendar.MINUTE, amount);
420474 }
421475
429483 * @return the new {@code Date} with the amount added
430484 * @throws IllegalArgumentException if the date is null
431485 */
432 public static Date addSeconds(Date date, int amount) {
486 public static Date addSeconds(final Date date, final int amount) {
433487 return add(date, Calendar.SECOND, amount);
434488 }
435489
443497 * @return the new {@code Date} with the amount added
444498 * @throws IllegalArgumentException if the date is null
445499 */
446 public static Date addMilliseconds(Date date, int amount) {
500 public static Date addMilliseconds(final Date date, final int amount) {
447501 return add(date, Calendar.MILLISECOND, amount);
448502 }
449503
458512 * @return the new {@code Date} with the amount added
459513 * @throws IllegalArgumentException if the date is null
460514 */
461 private static Date add(Date date, int calendarField, int amount) {
515 private static Date add(final Date date, final int calendarField, final int amount) {
462516 if (date == null) {
463517 throw new IllegalArgumentException("The date must not be null");
464518 }
465 Calendar c = Calendar.getInstance();
519 final Calendar c = Calendar.getInstance();
466520 c.setTime(date);
467521 c.add(calendarField, amount);
468522 return c.getTime();
479533 * @throws IllegalArgumentException if the date is null
480534 * @since 2.4
481535 */
482 public static Date setYears(Date date, int amount) {
536 public static Date setYears(final Date date, final int amount) {
483537 return set(date, Calendar.YEAR, amount);
484538 }
485539
494548 * @throws IllegalArgumentException if the date is null
495549 * @since 2.4
496550 */
497 public static Date setMonths(Date date, int amount) {
551 public static Date setMonths(final Date date, final int amount) {
498552 return set(date, Calendar.MONTH, amount);
499553 }
500554
509563 * @throws IllegalArgumentException if the date is null
510564 * @since 2.4
511565 */
512 public static Date setDays(Date date, int amount) {
566 public static Date setDays(final Date date, final int amount) {
513567 return set(date, Calendar.DAY_OF_MONTH, amount);
514568 }
515569
525579 * @throws IllegalArgumentException if the date is null
526580 * @since 2.4
527581 */
528 public static Date setHours(Date date, int amount) {
582 public static Date setHours(final Date date, final int amount) {
529583 return set(date, Calendar.HOUR_OF_DAY, amount);
530584 }
531585
540594 * @throws IllegalArgumentException if the date is null
541595 * @since 2.4
542596 */
543 public static Date setMinutes(Date date, int amount) {
597 public static Date setMinutes(final Date date, final int amount) {
544598 return set(date, Calendar.MINUTE, amount);
545599 }
546600
555609 * @throws IllegalArgumentException if the date is null
556610 * @since 2.4
557611 */
558 public static Date setSeconds(Date date, int amount) {
612 public static Date setSeconds(final Date date, final int amount) {
559613 return set(date, Calendar.SECOND, amount);
560614 }
561615
570624 * @throws IllegalArgumentException if the date is null
571625 * @since 2.4
572626 */
573 public static Date setMilliseconds(Date date, int amount) {
627 public static Date setMilliseconds(final Date date, final int amount) {
574628 return set(date, Calendar.MILLISECOND, amount);
575629 }
576630
587641 * @throws IllegalArgumentException if the date is null
588642 * @since 2.4
589643 */
590 private static Date set(Date date, int calendarField, int amount) {
644 private static Date set(final Date date, final int calendarField, final int amount) {
591645 if (date == null) {
592646 throw new IllegalArgumentException("The date must not be null");
593647 }
594648 // getInstance() returns a new object, so this method is thread safe.
595 Calendar c = Calendar.getInstance();
649 final Calendar c = Calendar.getInstance();
596650 c.setLenient(false);
597651 c.setTime(date);
598652 c.set(calendarField, amount);
601655
602656 //-----------------------------------------------------------------------
603657 /**
604 * Convert a {@code Date} into a {@code Calendar}.
658 * Converts a {@code Date} into a {@code Calendar}.
605659 *
606660 * @param date the date to convert to a Calendar
607661 * @return the created Calendar
608662 * @throws NullPointerException if null is passed in
609663 * @since 3.0
610664 */
611 public static Calendar toCalendar(Date date) {
612 Calendar c = Calendar.getInstance();
665 public static Calendar toCalendar(final Date date) {
666 final Calendar c = Calendar.getInstance();
613667 c.setTime(date);
614668 return c;
615669 }
616670
617671 //-----------------------------------------------------------------------
618672 /**
619 * <p>Round this date, leaving the field specified as the most
673 * <p>Rounds a date, leaving the field specified as the most
620674 * significant field.</p>
621675 *
622 * <p>For example, if you had the datetime of 28 Mar 2002
676 * <p>For example, if you had the date-time of 28 Mar 2002
623677 * 13:45:01.231, if this was passed with HOUR, it would return
624678 * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
625679 * would return 1 April 2002 0:00:00.000.</p>
641695 * @return the different rounded date, not null
642696 * @throws ArithmeticException if the year is over 280 million
643697 */
644 public static Date round(Date date, int field) {
698 public static Date round(final Date date, final int field) {
645699 if (date == null) {
646700 throw new IllegalArgumentException("The date must not be null");
647701 }
648 Calendar gval = Calendar.getInstance();
702 final Calendar gval = Calendar.getInstance();
649703 gval.setTime(date);
650704 modify(gval, field, MODIFY_ROUND);
651705 return gval.getTime();
652706 }
653707
654708 /**
655 * <p>Round this date, leaving the field specified as the most
709 * <p>Rounds a date, leaving the field specified as the most
656710 * significant field.</p>
657711 *
658 * <p>For example, if you had the datetime of 28 Mar 2002
712 * <p>For example, if you had the date-time of 28 Mar 2002
659713 * 13:45:01.231, if this was passed with HOUR, it would return
660714 * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
661715 * would return 1 April 2002 0:00:00.000.</p>
678732 * @throws IllegalArgumentException if the date is <code>null</code>
679733 * @throws ArithmeticException if the year is over 280 million
680734 */
681 public static Calendar round(Calendar date, int field) {
735 public static Calendar round(final Calendar date, final int field) {
682736 if (date == null) {
683737 throw new IllegalArgumentException("The date must not be null");
684738 }
685 Calendar rounded = (Calendar) date.clone();
739 final Calendar rounded = (Calendar) date.clone();
686740 modify(rounded, field, MODIFY_ROUND);
687741 return rounded;
688742 }
689743
690744 /**
691 * <p>Round this date, leaving the field specified as the most
745 * <p>Rounds a date, leaving the field specified as the most
692746 * significant field.</p>
693747 *
694 * <p>For example, if you had the datetime of 28 Mar 2002
748 * <p>For example, if you had the date-time of 28 Mar 2002
695749 * 13:45:01.231, if this was passed with HOUR, it would return
696750 * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
697751 * would return 1 April 2002 0:00:00.000.</p>
715769 * @throws ClassCastException if the object type is not a {@code Date} or {@code Calendar}
716770 * @throws ArithmeticException if the year is over 280 million
717771 */
718 public static Date round(Object date, int field) {
772 public static Date round(final Object date, final int field) {
719773 if (date == null) {
720774 throw new IllegalArgumentException("The date must not be null");
721775 }
730784
731785 //-----------------------------------------------------------------------
732786 /**
733 * <p>Truncate this date, leaving the field specified as the most
787 * <p>Truncates a date, leaving the field specified as the most
734788 * significant field.</p>
735789 *
736 * <p>For example, if you had the datetime of 28 Mar 2002
790 * <p>For example, if you had the date-time of 28 Mar 2002
737791 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
738792 * 2002 13:00:00.000. If this was passed with MONTH, it would
739793 * return 1 Mar 2002 0:00:00.000.</p>
744798 * @throws IllegalArgumentException if the date is <code>null</code>
745799 * @throws ArithmeticException if the year is over 280 million
746800 */
747 public static Date truncate(Date date, int field) {
801 public static Date truncate(final Date date, final int field) {
748802 if (date == null) {
749803 throw new IllegalArgumentException("The date must not be null");
750804 }
751 Calendar gval = Calendar.getInstance();
805 final Calendar gval = Calendar.getInstance();
752806 gval.setTime(date);
753807 modify(gval, field, MODIFY_TRUNCATE);
754808 return gval.getTime();
755809 }
756810
757811 /**
758 * <p>Truncate this date, leaving the field specified as the most
812 * <p>Truncates a date, leaving the field specified as the most
759813 * significant field.</p>
760814 *
761 * <p>For example, if you had the datetime of 28 Mar 2002
815 * <p>For example, if you had the date-time of 28 Mar 2002
762816 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
763817 * 2002 13:00:00.000. If this was passed with MONTH, it would
764818 * return 1 Mar 2002 0:00:00.000.</p>
769823 * @throws IllegalArgumentException if the date is <code>null</code>
770824 * @throws ArithmeticException if the year is over 280 million
771825 */
772 public static Calendar truncate(Calendar date, int field) {
826 public static Calendar truncate(final Calendar date, final int field) {
773827 if (date == null) {
774828 throw new IllegalArgumentException("The date must not be null");
775829 }
776 Calendar truncated = (Calendar) date.clone();
830 final Calendar truncated = (Calendar) date.clone();
777831 modify(truncated, field, MODIFY_TRUNCATE);
778832 return truncated;
779833 }
780834
781835 /**
782 * <p>Truncate this date, leaving the field specified as the most
836 * <p>Truncates a date, leaving the field specified as the most
783837 * significant field.</p>
784838 *
785 * <p>For example, if you had the datetime of 28 Mar 2002
839 * <p>For example, if you had the date-time of 28 Mar 2002
786840 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
787841 * 2002 13:00:00.000. If this was passed with MONTH, it would
788842 * return 1 Mar 2002 0:00:00.000.</p>
794848 * @throws ClassCastException if the object type is not a {@code Date} or {@code Calendar}
795849 * @throws ArithmeticException if the year is over 280 million
796850 */
797 public static Date truncate(Object date, int field) {
851 public static Date truncate(final Object date, final int field) {
798852 if (date == null) {
799853 throw new IllegalArgumentException("The date must not be null");
800854 }
809863
810864 //-----------------------------------------------------------------------
811865 /**
812 * <p>Ceil this date, leaving the field specified as the most
866 * <p>Gets a date ceiling, leaving the field specified as the most
813867 * significant field.</p>
814868 *
815 * <p>For example, if you had the datetime of 28 Mar 2002
869 * <p>For example, if you had the date-time of 28 Mar 2002
816870 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
817871 * 2002 14:00:00.000. If this was passed with MONTH, it would
818872 * return 1 Apr 2002 0:00:00.000.</p>
824878 * @throws ArithmeticException if the year is over 280 million
825879 * @since 2.5
826880 */
827 public static Date ceiling(Date date, int field) {
881 public static Date ceiling(final Date date, final int field) {
828882 if (date == null) {
829883 throw new IllegalArgumentException("The date must not be null");
830884 }
831 Calendar gval = Calendar.getInstance();
885 final Calendar gval = Calendar.getInstance();
832886 gval.setTime(date);
833887 modify(gval, field, MODIFY_CEILING);
834888 return gval.getTime();
835889 }
836890
837891 /**
838 * <p>Ceil this date, leaving the field specified as the most
892 * <p>Gets a date ceiling, leaving the field specified as the most
839893 * significant field.</p>
840894 *
841 * <p>For example, if you had the datetime of 28 Mar 2002
895 * <p>For example, if you had the date-time of 28 Mar 2002
842896 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
843 * 2002 13:00:00.000. If this was passed with MONTH, it would
844 * return 1 Mar 2002 0:00:00.000.</p>
897 * 2002 14:00:00.000. If this was passed with MONTH, it would
898 * return 1 Apr 2002 0:00:00.000.</p>
845899 *
846900 * @param date the date to work with, not null
847901 * @param field the field from {@code Calendar} or <code>SEMI_MONTH</code>
850904 * @throws ArithmeticException if the year is over 280 million
851905 * @since 2.5
852906 */
853 public static Calendar ceiling(Calendar date, int field) {
907 public static Calendar ceiling(final Calendar date, final int field) {
854908 if (date == null) {
855909 throw new IllegalArgumentException("The date must not be null");
856910 }
857 Calendar ceiled = (Calendar) date.clone();
911 final Calendar ceiled = (Calendar) date.clone();
858912 modify(ceiled, field, MODIFY_CEILING);
859913 return ceiled;
860914 }
861915
862916 /**
863 * <p>Ceil this date, leaving the field specified as the most
917 * <p>Gets a date ceiling, leaving the field specified as the most
864918 * significant field.</p>
865919 *
866 * <p>For example, if you had the datetime of 28 Mar 2002
920 * <p>For example, if you had the date-time of 28 Mar 2002
867921 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
868 * 2002 13:00:00.000. If this was passed with MONTH, it would
869 * return 1 Mar 2002 0:00:00.000.</p>
922 * 2002 14:00:00.000. If this was passed with MONTH, it would
923 * return 1 Apr 2002 0:00:00.000.</p>
870924 *
871925 * @param date the date to work with, either {@code Date} or {@code Calendar}, not null
872926 * @param field the field from {@code Calendar} or <code>SEMI_MONTH</code>
876930 * @throws ArithmeticException if the year is over 280 million
877931 * @since 2.5
878932 */
879 public static Date ceiling(Object date, int field) {
933 public static Date ceiling(final Object date, final int field) {
880934 if (date == null) {
881935 throw new IllegalArgumentException("The date must not be null");
882936 }
898952 * @param modType type to truncate, round or ceiling
899953 * @throws ArithmeticException if the year is over 280 million
900954 */
901 private static void modify(Calendar val, int field, int modType) {
955 private static void modify(final Calendar val, final int field, final int modType) {
902956 if (val.get(Calendar.YEAR) > 280000000) {
903957 throw new ArithmeticException("Calendar value too large for accurate calculations");
904958 }
913967 // Manually truncate milliseconds, seconds and minutes, rather than using
914968 // Calendar methods.
915969
916 Date date = val.getTime();
970 final Date date = val.getTime();
917971 long time = date.getTime();
918972 boolean done = false;
919973
920974 // truncate milliseconds
921 int millisecs = val.get(Calendar.MILLISECOND);
975 final int millisecs = val.get(Calendar.MILLISECOND);
922976 if (MODIFY_TRUNCATE == modType || millisecs < 500) {
923977 time = time - millisecs;
924978 }
927981 }
928982
929983 // truncate seconds
930 int seconds = val.get(Calendar.SECOND);
984 final int seconds = val.get(Calendar.SECOND);
931985 if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) {
932986 time = time - (seconds * 1000L);
933987 }
936990 }
937991
938992 // truncate minutes
939 int minutes = val.get(Calendar.MINUTE);
993 final int minutes = val.get(Calendar.MINUTE);
940994 if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) {
941995 time = time - (minutes * 60000L);
942996 }
9491003 // ----------------- Fix for LANG-59 ----------------------- END ----------------
9501004
9511005 boolean roundUp = false;
952 for (int[] aField : fields) {
953 for (int element : aField) {
1006 for (final int[] aField : fields) {
1007 for (final int element : aField) {
9541008 if (element == field) {
9551009 //This is our field... we stop looping
9561010 if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) {
10201074 break;
10211075 }
10221076 if (!offsetSet) {
1023 int min = val.getActualMinimum(aField[0]);
1024 int max = val.getActualMaximum(aField[0]);
1077 final int min = val.getActualMinimum(aField[0]);
1078 final int max = val.getActualMaximum(aField[0]);
10251079 //Calculate the offset from the minimum allowed value
10261080 offset = val.get(aField[0]) - min;
10271081 //Set roundUp if this is more than half way between the minimum and maximum
10381092
10391093 //-----------------------------------------------------------------------
10401094 /**
1041 * <p>This constructs an <code>Iterator</code> over each day in a date
1095 * <p>Constructs an <code>Iterator</code> over each day in a date
10421096 * range defined by a focus date and range style.</p>
10431097 *
10441098 * <p>For instance, passing Thursday, July 4, 2002 and a
10611115 * @throws IllegalArgumentException if the date is <code>null</code>
10621116 * @throws IllegalArgumentException if the rangeStyle is invalid
10631117 */
1064 public static Iterator<Calendar> iterator(Date focus, int rangeStyle) {
1118 public static Iterator<Calendar> iterator(final Date focus, final int rangeStyle) {
10651119 if (focus == null) {
10661120 throw new IllegalArgumentException("The date must not be null");
10671121 }
1068 Calendar gval = Calendar.getInstance();
1122 final Calendar gval = Calendar.getInstance();
10691123 gval.setTime(focus);
10701124 return iterator(gval, rangeStyle);
10711125 }
10721126
10731127 /**
1074 * <p>This constructs an <code>Iterator</code> over each day in a date
1128 * <p>Constructs an <code>Iterator</code> over each day in a date
10751129 * range defined by a focus date and range style.</p>
10761130 *
10771131 * <p>For instance, passing Thursday, July 4, 2002 and a
10941148 * @throws IllegalArgumentException if the date is <code>null</code>
10951149 * @throws IllegalArgumentException if the rangeStyle is invalid
10961150 */
1097 public static Iterator<Calendar> iterator(Calendar focus, int rangeStyle) {
1151 public static Iterator<Calendar> iterator(final Calendar focus, final int rangeStyle) {
10981152 if (focus == null) {
10991153 throw new IllegalArgumentException("The date must not be null");
11001154 }
11671221 }
11681222
11691223 /**
1170 * <p>This constructs an <code>Iterator</code> over each day in a date
1224 * <p>Constructs an <code>Iterator</code> over each day in a date
11711225 * range defined by a focus date and range style.</p>
11721226 *
11731227 * <p>For instance, passing Thursday, July 4, 2002 and a
11821236 * @throws IllegalArgumentException if the date is <code>null</code>
11831237 * @throws ClassCastException if the object type is not a {@code Date} or {@code Calendar}
11841238 */
1185 public static Iterator<?> iterator(Object focus, int rangeStyle) {
1239 public static Iterator<?> iterator(final Object focus, final int rangeStyle) {
11861240 if (focus == null) {
11871241 throw new IllegalArgumentException("The date must not be null");
11881242 }
12281282 * fragment is not supported
12291283 * @since 2.4
12301284 */
1231 public static long getFragmentInMilliseconds(Date date, int fragment) {
1285 public static long getFragmentInMilliseconds(final Date date, final int fragment) {
12321286 return getFragment(date, fragment, Calendar.MILLISECOND);
12331287 }
12341288
12681322 * fragment is not supported
12691323 * @since 2.4
12701324 */
1271 public static long getFragmentInSeconds(Date date, int fragment) {
1325 public static long getFragmentInSeconds(final Date date, final int fragment) {
12721326 return getFragment(date, fragment, Calendar.SECOND);
12731327 }
12741328
13081362 * fragment is not supported
13091363 * @since 2.4
13101364 */
1311 public static long getFragmentInMinutes(Date date, int fragment) {
1365 public static long getFragmentInMinutes(final Date date, final int fragment) {
13121366 return getFragment(date, fragment, Calendar.MINUTE);
13131367 }
13141368
13481402 * fragment is not supported
13491403 * @since 2.4
13501404 */
1351 public static long getFragmentInHours(Date date, int fragment) {
1405 public static long getFragmentInHours(final Date date, final int fragment) {
13521406 return getFragment(date, fragment, Calendar.HOUR_OF_DAY);
13531407 }
13541408
13881442 * fragment is not supported
13891443 * @since 2.4
13901444 */
1391 public static long getFragmentInDays(Date date, int fragment) {
1445 public static long getFragmentInDays(final Date date, final int fragment) {
13921446 return getFragment(date, fragment, Calendar.DAY_OF_YEAR);
13931447 }
13941448
14281482 * fragment is not supported
14291483 * @since 2.4
14301484 */
1431 public static long getFragmentInMilliseconds(Calendar calendar, int fragment) {
1485 public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment) {
14321486 return getFragment(calendar, fragment, Calendar.MILLISECOND);
14331487 }
14341488 /**
14671521 * fragment is not supported
14681522 * @since 2.4
14691523 */
1470 public static long getFragmentInSeconds(Calendar calendar, int fragment) {
1524 public static long getFragmentInSeconds(final Calendar calendar, final int fragment) {
14711525 return getFragment(calendar, fragment, Calendar.SECOND);
14721526 }
14731527
15071561 * fragment is not supported
15081562 * @since 2.4
15091563 */
1510 public static long getFragmentInMinutes(Calendar calendar, int fragment) {
1564 public static long getFragmentInMinutes(final Calendar calendar, final int fragment) {
15111565 return getFragment(calendar, fragment, Calendar.MINUTE);
15121566 }
15131567
15471601 * fragment is not supported
15481602 * @since 2.4
15491603 */
1550 public static long getFragmentInHours(Calendar calendar, int fragment) {
1604 public static long getFragmentInHours(final Calendar calendar, final int fragment) {
15511605 return getFragment(calendar, fragment, Calendar.HOUR_OF_DAY);
15521606 }
15531607
15891643 * fragment is not supported
15901644 * @since 2.4
15911645 */
1592 public static long getFragmentInDays(Calendar calendar, int fragment) {
1646 public static long getFragmentInDays(final Calendar calendar, final int fragment) {
15931647 return getFragment(calendar, fragment, Calendar.DAY_OF_YEAR);
15941648 }
15951649
15961650 /**
1597 * Date-version for fragment-calculation in any unit
1651 * Gets a Date fragment for any unit.
15981652 *
15991653 * @param date the date to work with, not null
16001654 * @param fragment the Calendar field part of date to calculate
16041658 * fragment is not supported
16051659 * @since 2.4
16061660 */
1607 private static long getFragment(Date date, int fragment, int unit) {
1661 private static long getFragment(final Date date, final int fragment, final int unit) {
16081662 if(date == null) {
16091663 throw new IllegalArgumentException("The date must not be null");
16101664 }
1611 Calendar calendar = Calendar.getInstance();
1665 final Calendar calendar = Calendar.getInstance();
16121666 calendar.setTime(date);
16131667 return getFragment(calendar, fragment, unit);
16141668 }
16151669
16161670 /**
1617 * Calendar-version for fragment-calculation in any unit
1671 * Gets a Calendar fragment for any unit.
16181672 *
16191673 * @param calendar the calendar to work with, not null
16201674 * @param fragment the Calendar field part of calendar to calculate
16241678 * fragment is not supported
16251679 * @since 2.4
16261680 */
1627 private static long getFragment(Calendar calendar, int fragment, int unit) {
1681 private static long getFragment(final Calendar calendar, final int fragment, final int unit) {
16281682 if(calendar == null) {
16291683 throw new IllegalArgumentException("The date must not be null");
16301684 }
1631 long millisPerUnit = getMillisPerUnit(unit);
1685 final long millisPerUnit = getMillisPerUnit(unit);
16321686 long result = 0;
16331687
16341688 // Fragments bigger than a day require a breakdown to days
16791733 * @see #truncatedEquals(Date, Date, int)
16801734 * @since 3.0
16811735 */
1682 public static boolean truncatedEquals(Calendar cal1, Calendar cal2, int field) {
1736 public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field) {
16831737 return truncatedCompareTo(cal1, cal2, field) == 0;
16841738 }
16851739
16961750 * @see #truncatedEquals(Calendar, Calendar, int)
16971751 * @since 3.0
16981752 */
1699 public static boolean truncatedEquals(Date date1, Date date2, int field) {
1753 public static boolean truncatedEquals(final Date date1, final Date date2, final int field) {
17001754 return truncatedCompareTo(date1, date2, field) == 0;
17011755 }
17021756
17141768 * @see #truncatedCompareTo(Date, Date, int)
17151769 * @since 3.0
17161770 */
1717 public static int truncatedCompareTo(Calendar cal1, Calendar cal2, int field) {
1718 Calendar truncatedCal1 = truncate(cal1, field);
1719 Calendar truncatedCal2 = truncate(cal2, field);
1771 public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field) {
1772 final Calendar truncatedCal1 = truncate(cal1, field);
1773 final Calendar truncatedCal2 = truncate(cal2, field);
17201774 return truncatedCal1.compareTo(truncatedCal2);
17211775 }
17221776
17341788 * @see #truncatedCompareTo(Date, Date, int)
17351789 * @since 3.0
17361790 */
1737 public static int truncatedCompareTo(Date date1, Date date2, int field) {
1738 Date truncatedDate1 = truncate(date1, field);
1739 Date truncatedDate2 = truncate(date2, field);
1791 public static int truncatedCompareTo(final Date date1, final Date date2, final int field) {
1792 final Date truncatedDate1 = truncate(date1, field);
1793 final Date truncatedDate2 = truncate(date2, field);
17401794 return truncatedDate1.compareTo(truncatedDate2);
17411795 }
17421796
17491803 * @throws IllegalArgumentException if date can't be represented in milliseconds
17501804 * @since 2.4
17511805 */
1752 private static long getMillisPerUnit(int unit) {
1806 private static long getMillisPerUnit(final int unit) {
17531807 long result = Long.MAX_VALUE;
17541808 switch (unit) {
17551809 case Calendar.DAY_OF_YEAR:
17851839 * Constructs a DateIterator that ranges from one date to another.
17861840 *
17871841 * @param startFinal start date (inclusive)
1788 * @param endFinal end date (not inclusive)
1842 * @param endFinal end date (inclusive)
17891843 */
1790 DateIterator(Calendar startFinal, Calendar endFinal) {
1844 DateIterator(final Calendar startFinal, final Calendar endFinal) {
17911845 super();
17921846 this.endFinal = endFinal;
17931847 spot = startFinal;
17991853 *
18001854 * @return <code>true</code> if the iterator has yet to reach the end date
18011855 */
1856 @Override
18021857 public boolean hasNext() {
18031858 return spot.before(endFinal);
18041859 }
18081863 *
18091864 * @return Object calendar for the next date
18101865 */
1866 @Override
18111867 public Calendar next() {
18121868 if (spot.equals(endFinal)) {
18131869 throw new NoSuchElementException();
18221878 * @throws UnsupportedOperationException
18231879 * @see java.util.Iterator#remove()
18241880 */
1881 @Override
18251882 public void remove() {
18261883 throw new UnsupportedOperationException();
18271884 }
3838 * </table>
3939 *
4040 * @since 2.1
41 * @version $Id: DurationFormatUtils.java 1144993 2011-07-11 00:51:16Z ggregory $
41 * @version $Id: DurationFormatUtils.java 1478487 2013-05-02 19:04:35Z ggregory $
4242 */
4343 public class DurationFormatUtils {
4444
7171 * @param durationMillis the duration to format
7272 * @return the formatted duration, not null
7373 */
74 public static String formatDurationHMS(long durationMillis) {
74 public static String formatDurationHMS(final long durationMillis) {
7575 return formatDuration(durationMillis, "H:mm:ss.SSS");
7676 }
7777
8686 * @param durationMillis the duration to format
8787 * @return the formatted duration, not null
8888 */
89 public static String formatDurationISO(long durationMillis) {
89 public static String formatDurationISO(final long durationMillis) {
9090 return formatDuration(durationMillis, ISO_EXTENDED_FORMAT_PATTERN, false);
9191 }
9292
101101 * @param format the way in which to format the duration, not null
102102 * @return the formatted duration, not null
103103 */
104 public static String formatDuration(long durationMillis, String format) {
104 public static String formatDuration(final long durationMillis, final String format) {
105105 return formatDuration(durationMillis, format, true);
106106 }
107107
118118 * @param padWithZeros whether to pad the left hand side of numbers with 0's
119119 * @return the formatted duration, not null
120120 */
121 public static String formatDuration(long durationMillis, String format, boolean padWithZeros) {
122
123 Token[] tokens = lexx(format);
121 public static String formatDuration(long durationMillis, final String format, final boolean padWithZeros) {
122
123 final Token[] tokens = lexx(format);
124124
125125 int days = 0;
126126 int hours = 0;
163163 * @return the formatted text in days/hours/minutes/seconds, not null
164164 */
165165 public static String formatDurationWords(
166 long durationMillis,
167 boolean suppressLeadingZeroElements,
168 boolean suppressTrailingZeroElements) {
166 final long durationMillis,
167 final boolean suppressLeadingZeroElements,
168 final boolean suppressTrailingZeroElements) {
169169
170170 // This method is generally replacable by the format method, but
171171 // there are a series of tweaks and special cases that require
225225 * @param endMillis the end of the duration to format
226226 * @return the formatted duration, not null
227227 */
228 public static String formatPeriodISO(long startMillis, long endMillis) {
228 public static String formatPeriodISO(final long startMillis, final long endMillis) {
229229 return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault());
230230 }
231231
238238 * @param format the way in which to format the duration, not null
239239 * @return the formatted duration, not null
240240 */
241 public static String formatPeriod(long startMillis, long endMillis, String format) {
241 public static String formatPeriod(final long startMillis, final long endMillis, final String format) {
242242 return formatPeriod(startMillis, endMillis, format, true, TimeZone.getDefault());
243243 }
244244
265265 * @param timezone the millis are defined in
266266 * @return the formatted duration, not null
267267 */
268 public static String formatPeriod(long startMillis, long endMillis, String format, boolean padWithZeros,
269 TimeZone timezone) {
268 public static String formatPeriod(final long startMillis, final long endMillis, final String format, final boolean padWithZeros,
269 final TimeZone timezone) {
270270
271271 // Used to optimise for differences under 28 days and
272272 // called formatDuration(millis, format); however this did not work
274274 // TODO: Compare performance to see if anything was lost by
275275 // losing this optimisation.
276276
277 Token[] tokens = lexx(format);
277 final Token[] tokens = lexx(format);
278278
279279 // timezones get funky around 0, so normalizing everything to GMT
280280 // stops the hours being off
281 Calendar start = Calendar.getInstance(timezone);
281 final Calendar start = Calendar.getInstance(timezone);
282282 start.setTime(new Date(startMillis));
283 Calendar end = Calendar.getInstance(timezone);
283 final Calendar end = Calendar.getInstance(timezone);
284284 end.setTime(new Date(endMillis));
285285
286286 // initial estimates
338338 target -= 1;
339339 }
340340
341 while ( (start.get(Calendar.YEAR) != target)) {
341 while (start.get(Calendar.YEAR) != target) {
342342 days += start.getActualMaximum(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);
343343
344344 // Not sure I grok why this is needed, but the brutal tests show it is
410410 * @param padWithZeros whether to pad
411411 * @return the formatted string
412412 */
413 static String format(Token[] tokens, int years, int months, int days, int hours, int minutes, int seconds,
414 int milliseconds, boolean padWithZeros) {
415 StringBuffer buffer = new StringBuffer();
413 static String format(final Token[] tokens, final int years, final int months, final int days, final int hours, final int minutes, final int seconds,
414 int milliseconds, final boolean padWithZeros) {
415 final StringBuilder buffer = new StringBuilder();
416416 boolean lastOutputSeconds = false;
417 int sz = tokens.length;
417 final int sz = tokens.length;
418418 for (int i = 0; i < sz; i++) {
419 Token token = tokens[i];
420 Object value = token.getValue();
421 int count = token.getCount();
422 if (value instanceof StringBuffer) {
419 final Token token = tokens[i];
420 final Object value = token.getValue();
421 final int count = token.getCount();
422 if (value instanceof StringBuilder) {
423423 buffer.append(value.toString());
424424 } else {
425425 if (value == y) {
449449 } else if (value == S) {
450450 if (lastOutputSeconds) {
451451 milliseconds += 1000;
452 String str = padWithZeros
452 final String str = padWithZeros
453453 ? StringUtils.leftPad(Integer.toString(milliseconds), count, '0')
454454 : Integer.toString(milliseconds);
455455 buffer.append(str.substring(1));
479479 * @param format the format to parse, not null
480480 * @return array of Token[]
481481 */
482 static Token[] lexx(String format) {
483 char[] array = format.toCharArray();
484 ArrayList<Token> list = new ArrayList<Token>(array.length);
482 static Token[] lexx(final String format) {
483 final char[] array = format.toCharArray();
484 final ArrayList<Token> list = new ArrayList<Token>(array.length);
485485
486486 boolean inLiteral = false;
487 StringBuffer buffer = null;
487 // Although the buffer is stored in a Token, the Tokens are only
488 // used internally, so cannot be accessed by other threads
489 StringBuilder buffer = null;
488490 Token previous = null;
489 int sz = array.length;
490 for(int i=0; i<sz; i++) {
491 char ch = array[i];
492 if(inLiteral && ch != '\'') {
491 final int sz = array.length;
492 for (int i = 0; i < sz; i++) {
493 final char ch = array[i];
494 if (inLiteral && ch != '\'') {
493495 buffer.append(ch); // buffer can't be null if inLiteral is true
494496 continue;
495497 }
496498 Object value = null;
497 switch(ch) {
498 // TODO: Need to handle escaping of '
499 case '\'' :
500 if(inLiteral) {
501 buffer = null;
502 inLiteral = false;
503 } else {
504 buffer = new StringBuffer();
505 list.add(new Token(buffer));
506 inLiteral = true;
507 }
508 break;
509 case 'y' : value = y; break;
510 case 'M' : value = M; break;
511 case 'd' : value = d; break;
512 case 'H' : value = H; break;
513 case 'm' : value = m; break;
514 case 's' : value = s; break;
515 case 'S' : value = S; break;
516 default :
517 if(buffer == null) {
518 buffer = new StringBuffer();
519 list.add(new Token(buffer));
520 }
521 buffer.append(ch);
522 }
523
524 if(value != null) {
525 if(previous != null && previous.getValue() == value) {
499 switch (ch) {
500 // TODO: Need to handle escaping of '
501 case '\'':
502 if (inLiteral) {
503 buffer = null;
504 inLiteral = false;
505 } else {
506 buffer = new StringBuilder();
507 list.add(new Token(buffer));
508 inLiteral = true;
509 }
510 break;
511 case 'y':
512 value = y;
513 break;
514 case 'M':
515 value = M;
516 break;
517 case 'd':
518 value = d;
519 break;
520 case 'H':
521 value = H;
522 break;
523 case 'm':
524 value = m;
525 break;
526 case 's':
527 value = s;
528 break;
529 case 'S':
530 value = S;
531 break;
532 default:
533 if (buffer == null) {
534 buffer = new StringBuilder();
535 list.add(new Token(buffer));
536 }
537 buffer.append(ch);
538 }
539
540 if (value != null) {
541 if (previous != null && previous.getValue() == value) {
526542 previous.increment();
527543 } else {
528 Token token = new Token(value);
529 list.add(token);
544 final Token token = new Token(value);
545 list.add(token);
530546 previous = token;
531547 }
532 buffer = null;
533 }
534 }
535 return list.toArray( new Token[list.size()] );
548 buffer = null;
549 }
550 }
551 return list.toArray(new Token[list.size()]);
536552 }
537553
538554 //-----------------------------------------------------------------------
548564 * @param value to look for
549565 * @return boolean <code>true</code> if contained
550566 */
551 static boolean containsTokenWithValue(Token[] tokens, Object value) {
552 int sz = tokens.length;
567 static boolean containsTokenWithValue(final Token[] tokens, final Object value) {
568 final int sz = tokens.length;
553569 for (int i = 0; i < sz; i++) {
554570 if (tokens[i].getValue() == value) {
555571 return true;
566582 *
567583 * @param value to wrap
568584 */
569 Token(Object value) {
585 Token(final Object value) {
570586 this.value = value;
571587 this.count = 1;
572588 }
578594 * @param value to wrap
579595 * @param count to wrap
580596 */
581 Token(Object value, int count) {
597 Token(final Object value, final int count) {
582598 this.value = value;
583599 this.count = count;
584600 }
615631 * @return boolean <code>true</code> if equal
616632 */
617633 @Override
618 public boolean equals(Object obj2) {
634 public boolean equals(final Object obj2) {
619635 if (obj2 instanceof Token) {
620 Token tok2 = (Token) obj2;
636 final Token tok2 = (Token) obj2;
621637 if (this.value.getClass() != tok2.value.getClass()) {
622638 return false;
623639 }
624640 if (this.count != tok2.count) {
625641 return false;
626642 }
627 if (this.value instanceof StringBuffer) {
643 if (this.value instanceof StringBuilder) {
628644 return this.value.toString().equals(tok2.value.toString());
629645 } else if (this.value instanceof Number) {
630646 return this.value.equals(tok2.value);
1515 */
1616 package org.apache.commons.lang3.time;
1717
18 import java.io.IOException;
19 import java.io.ObjectInputStream;
2018 import java.text.DateFormat;
21 import java.text.DateFormatSymbols;
2219 import java.text.FieldPosition;
2320 import java.text.Format;
21 import java.text.ParseException;
2422 import java.text.ParsePosition;
25 import java.util.ArrayList;
2623 import java.util.Calendar;
2724 import java.util.Date;
28 import java.util.GregorianCalendar;
29 import java.util.List;
3025 import java.util.Locale;
3126 import java.util.TimeZone;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ConcurrentMap;
34
35 import org.apache.commons.lang3.Validate;
3627
3728 /**
3829 * <p>FastDateFormat is a fast and thread-safe version of
3930 * {@link java.text.SimpleDateFormat}.</p>
4031 *
4132 * <p>This class can be used as a direct replacement to
42 * {@code SimpleDateFormat} in most formatting situations.
33 * {@code SimpleDateFormat} in most formatting and parsing situations.
4334 * This class is especially useful in multi-threaded server environments.
4435 * {@code SimpleDateFormat} is not thread-safe in any JDK version,
4536 * nor will it be as Sun have closed the bug/RFE.
4637 * </p>
4738 *
48 * <p>Only formatting is supported, but all patterns are compatible with
39 * <p>All patterns are compatible with
4940 * SimpleDateFormat (except time zones and some year patterns - see below).</p>
41 *
42 * <p>Since 3.2, FastDateFormat supports parsing as well as printing.</p>
5043 *
5144 * <p>Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent
5245 * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}).
6457 * versions. FastDateFormat implements the behavior of Java 7.</p>
6558 *
6659 * @since 2.0
67 * @version $Id: FastDateFormat.java 1146138 2011-07-13 17:01:37Z joehni $
60 * @version $Id: FastDateFormat.java 1533798 2013-10-19 17:46:57Z tn $
6861 */
69 public class FastDateFormat extends Format {
70 // A lot of the speed in this class comes from caching, but some comes
71 // from the special int to StringBuffer conversion.
72 //
73 // The following produces a padded 2 digit number:
74 // buffer.append((char)(value / 10 + '0'));
75 // buffer.append((char)(value % 10 + '0'));
76 //
77 // Note that the fastest append to StringBuffer is a single char (used here).
78 // Note that Integer.toString() is not called, the conversion is simply
79 // taking the value and adding (mathematically) the ASCII value for '0'.
80 // So, don't change this code! It works and is very fast.
81
62 public class FastDateFormat extends Format implements DateParser, DatePrinter {
8263 /**
8364 * Required for serialization support.
8465 *
8566 * @see java.io.Serializable
8667 */
87 private static final long serialVersionUID = 1L;
68 private static final long serialVersionUID = 2L;
8869
8970 /**
9071 * FULL locale dependent date or time style.
10586
10687 private static final FormatCache<FastDateFormat> cache= new FormatCache<FastDateFormat>() {
10788 @Override
108 protected FastDateFormat createInstance(String pattern, TimeZone timeZone, Locale locale) {
89 protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) {
10990 return new FastDateFormat(pattern, timeZone, locale);
11091 }
11192 };
11293
113 private static ConcurrentMap<TimeZoneDisplayKey, String> cTimeZoneDisplayCache =
114 new ConcurrentHashMap<TimeZoneDisplayKey, String>(7);
115
116 /**
117 * The pattern.
118 */
119 private final String mPattern;
120 /**
121 * The time zone.
122 */
123 private final TimeZone mTimeZone;
124 /**
125 * The locale.
126 */
127 private final Locale mLocale;
128 /**
129 * The parsed rules.
130 */
131 private transient Rule[] mRules;
132 /**
133 * The estimated maximum length.
134 */
135 private transient int mMaxLengthEstimate;
136
94 private final FastDatePrinter printer;
95 private final FastDateParser parser;
96
13797 //-----------------------------------------------------------------------
13898 /**
13999 * <p>Gets a formatter instance using the default pattern in the
142102 * @return a date/time formatter
143103 */
144104 public static FastDateFormat getInstance() {
145 return cache.getDateTimeInstance(SHORT, SHORT, null, null);
105 return cache.getInstance();
146106 }
147107
148108 /**
154114 * @return a pattern based date/time formatter
155115 * @throws IllegalArgumentException if pattern is invalid
156116 */
157 public static FastDateFormat getInstance(String pattern) {
117 public static FastDateFormat getInstance(final String pattern) {
158118 return cache.getInstance(pattern, null, null);
159119 }
160120
169129 * @return a pattern based date/time formatter
170130 * @throws IllegalArgumentException if pattern is invalid
171131 */
172 public static FastDateFormat getInstance(String pattern, TimeZone timeZone) {
132 public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone) {
173133 return cache.getInstance(pattern, timeZone, null);
174134 }
175135
183143 * @return a pattern based date/time formatter
184144 * @throws IllegalArgumentException if pattern is invalid
185145 */
186 public static FastDateFormat getInstance(String pattern, Locale locale) {
146 public static FastDateFormat getInstance(final String pattern, final Locale locale) {
187147 return cache.getInstance(pattern, null, locale);
188148 }
189149
200160 * @throws IllegalArgumentException if pattern is invalid
201161 * or {@code null}
202162 */
203 public static FastDateFormat getInstance(String pattern, TimeZone timeZone, Locale locale) {
163 public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone, final Locale locale) {
204164 return cache.getInstance(pattern, timeZone, locale);
205165 }
206166
215175 * pattern defined
216176 * @since 2.1
217177 */
218 public static FastDateFormat getDateInstance(int style) {
219 return cache.getDateTimeInstance(style, null, null, null);
178 public static FastDateFormat getDateInstance(final int style) {
179 return cache.getDateInstance(style, null, null);
220180 }
221181
222182 /**
230190 * pattern defined
231191 * @since 2.1
232192 */
233 public static FastDateFormat getDateInstance(int style, Locale locale) {
234 return cache.getDateTimeInstance(style, null, null, locale);
193 public static FastDateFormat getDateInstance(final int style, final Locale locale) {
194 return cache.getDateInstance(style, null, locale);
235195 }
236196
237197 /**
246206 * pattern defined
247207 * @since 2.1
248208 */
249 public static FastDateFormat getDateInstance(int style, TimeZone timeZone) {
250 return cache.getDateTimeInstance(style, null, timeZone, null);
209 public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone) {
210 return cache.getDateInstance(style, timeZone, null);
251211 }
252212
253213 /**
262222 * @throws IllegalArgumentException if the Locale has no date
263223 * pattern defined
264224 */
265 public static FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
266 return cache.getDateTimeInstance(style, null, timeZone, locale);
225 public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone, final Locale locale) {
226 return cache.getDateInstance(style, timeZone, locale);
267227 }
268228
269229 //-----------------------------------------------------------------------
277237 * pattern defined
278238 * @since 2.1
279239 */
280 public static FastDateFormat getTimeInstance(int style) {
281 return cache.getDateTimeInstance(null, style, null, null);
240 public static FastDateFormat getTimeInstance(final int style) {
241 return cache.getTimeInstance(style, null, null);
282242 }
283243
284244 /**
292252 * pattern defined
293253 * @since 2.1
294254 */
295 public static FastDateFormat getTimeInstance(int style, Locale locale) {
296 return cache.getDateTimeInstance(null, style, null, locale);
255 public static FastDateFormat getTimeInstance(final int style, final Locale locale) {
256 return cache.getTimeInstance(style, null, locale);
297257 }
298258
299259 /**
308268 * pattern defined
309269 * @since 2.1
310270 */
311 public static FastDateFormat getTimeInstance(int style, TimeZone timeZone) {
312 return cache.getDateTimeInstance(null, style, timeZone, null);
271 public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone) {
272 return cache.getTimeInstance(style, timeZone, null);
313273 }
314274
315275 /**
324284 * @throws IllegalArgumentException if the Locale has no time
325285 * pattern defined
326286 */
327 public static FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) {
328 return cache.getDateTimeInstance(null, style, timeZone, locale);
287 public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone, final Locale locale) {
288 return cache.getTimeInstance(style, timeZone, locale);
329289 }
330290
331291 //-----------------------------------------------------------------------
340300 * pattern defined
341301 * @since 2.1
342302 */
343 public static FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle) {
303 public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle) {
344304 return cache.getDateTimeInstance(dateStyle, timeStyle, null, null);
345305 }
346306
356316 * pattern defined
357317 * @since 2.1
358318 */
359 public static FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) {
319 public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle, final Locale locale) {
360320 return cache.getDateTimeInstance(dateStyle, timeStyle, null, locale);
361321 }
362322
373333 * pattern defined
374334 * @since 2.1
375335 */
376 public static FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone) {
336 public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone) {
377337 return getDateTimeInstance(dateStyle, timeStyle, timeZone, null);
378338 }
379339 /**
390350 * pattern defined
391351 */
392352 public static FastDateFormat getDateTimeInstance(
393 int dateStyle, int timeStyle, TimeZone timeZone, Locale locale) {
353 final int dateStyle, final int timeStyle, final TimeZone timeZone, final Locale locale) {
394354 return cache.getDateTimeInstance(dateStyle, timeStyle, timeZone, locale);
395 }
396
397 //-----------------------------------------------------------------------
398 /**
399 * <p>Gets the time zone display name, using a cache for performance.</p>
400 *
401 * @param tz the zone to query
402 * @param daylight true if daylight savings
403 * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT}
404 * @param locale the locale to use
405 * @return the textual name of the time zone
406 */
407 static String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
408 TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale);
409 String value = cTimeZoneDisplayCache.get(key);
410 if (value == null) {
411 // This is a very slow call, so cache the results.
412 value = tz.getDisplayName(daylight, style, locale);
413 String prior = cTimeZoneDisplayCache.putIfAbsent(key, value);
414 if (prior != null) {
415 value= prior;
416 }
417 }
418 return value;
419355 }
420356
421357 // Constructor
428364 * @param locale non-null locale to use
429365 * @throws NullPointerException if pattern, timeZone, or locale is null.
430366 */
431 protected FastDateFormat(String pattern, TimeZone timeZone, Locale locale) {
432 mPattern = pattern;
433 mTimeZone = timeZone;
434 mLocale = locale;
435
436 init();
437 }
438
439 /**
440 * <p>Initializes the instance for first use.</p>
441 */
442 private void init() {
443 List<Rule> rulesList = parsePattern();
444 mRules = rulesList.toArray(new Rule[rulesList.size()]);
445
446 int len = 0;
447 for (int i=mRules.length; --i >= 0; ) {
448 len += mRules[i].estimateLength();
449 }
450
451 mMaxLengthEstimate = len;
452 }
453
454 // Parse the pattern
455 //-----------------------------------------------------------------------
456 /**
457 * <p>Returns a list of Rules given a pattern.</p>
458 *
459 * @return a {@code List} of Rule objects
460 * @throws IllegalArgumentException if pattern is invalid
461 */
462 protected List<Rule> parsePattern() {
463 DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
464 List<Rule> rules = new ArrayList<Rule>();
465
466 String[] ERAs = symbols.getEras();
467 String[] months = symbols.getMonths();
468 String[] shortMonths = symbols.getShortMonths();
469 String[] weekdays = symbols.getWeekdays();
470 String[] shortWeekdays = symbols.getShortWeekdays();
471 String[] AmPmStrings = symbols.getAmPmStrings();
472
473 int length = mPattern.length();
474 int[] indexRef = new int[1];
475
476 for (int i = 0; i < length; i++) {
477 indexRef[0] = i;
478 String token = parseToken(mPattern, indexRef);
479 i = indexRef[0];
480
481 int tokenLen = token.length();
482 if (tokenLen == 0) {
483 break;
484 }
485
486 Rule rule;
487 char c = token.charAt(0);
488
489 switch (c) {
490 case 'G': // era designator (text)
491 rule = new TextField(Calendar.ERA, ERAs);
492 break;
493 case 'y': // year (number)
494 if (tokenLen == 2) {
495 rule = TwoDigitYearField.INSTANCE;
496 } else {
497 rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
498 }
499 break;
500 case 'M': // month in year (text and number)
501 if (tokenLen >= 4) {
502 rule = new TextField(Calendar.MONTH, months);
503 } else if (tokenLen == 3) {
504 rule = new TextField(Calendar.MONTH, shortMonths);
505 } else if (tokenLen == 2) {
506 rule = TwoDigitMonthField.INSTANCE;
507 } else {
508 rule = UnpaddedMonthField.INSTANCE;
509 }
510 break;
511 case 'd': // day in month (number)
512 rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
513 break;
514 case 'h': // hour in am/pm (number, 1..12)
515 rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
516 break;
517 case 'H': // hour in day (number, 0..23)
518 rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
519 break;
520 case 'm': // minute in hour (number)
521 rule = selectNumberRule(Calendar.MINUTE, tokenLen);
522 break;
523 case 's': // second in minute (number)
524 rule = selectNumberRule(Calendar.SECOND, tokenLen);
525 break;
526 case 'S': // millisecond (number)
527 rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
528 break;
529 case 'E': // day in week (text)
530 rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
531 break;
532 case 'D': // day in year (number)
533 rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
534 break;
535 case 'F': // day of week in month (number)
536 rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
537 break;
538 case 'w': // week in year (number)
539 rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
540 break;
541 case 'W': // week in month (number)
542 rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
543 break;
544 case 'a': // am/pm marker (text)
545 rule = new TextField(Calendar.AM_PM, AmPmStrings);
546 break;
547 case 'k': // hour in day (1..24)
548 rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
549 break;
550 case 'K': // hour in am/pm (0..11)
551 rule = selectNumberRule(Calendar.HOUR, tokenLen);
552 break;
553 case 'z': // time zone (text)
554 if (tokenLen >= 4) {
555 rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
556 } else {
557 rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
558 }
559 break;
560 case 'Z': // time zone (value)
561 if (tokenLen == 1) {
562 rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
563 } else {
564 rule = TimeZoneNumberRule.INSTANCE_COLON;
565 }
566 break;
567 case '\'': // literal text
568 String sub = token.substring(1);
569 if (sub.length() == 1) {
570 rule = new CharacterLiteral(sub.charAt(0));
571 } else {
572 rule = new StringLiteral(sub);
573 }
574 break;
575 default:
576 throw new IllegalArgumentException("Illegal pattern component: " + token);
577 }
578
579 rules.add(rule);
580 }
581
582 return rules;
583 }
584
585 /**
586 * <p>Performs the parsing of tokens.</p>
587 *
588 * @param pattern the pattern
589 * @param indexRef index references
590 * @return parsed token
591 */
592 protected String parseToken(String pattern, int[] indexRef) {
593 StringBuilder buf = new StringBuilder();
594
595 int i = indexRef[0];
596 int length = pattern.length();
597
598 char c = pattern.charAt(i);
599 if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
600 // Scan a run of the same character, which indicates a time
601 // pattern.
602 buf.append(c);
603
604 while (i + 1 < length) {
605 char peek = pattern.charAt(i + 1);
606 if (peek == c) {
607 buf.append(c);
608 i++;
609 } else {
610 break;
611 }
612 }
613 } else {
614 // This will identify token as text.
615 buf.append('\'');
616
617 boolean inLiteral = false;
618
619 for (; i < length; i++) {
620 c = pattern.charAt(i);
621
622 if (c == '\'') {
623 if (i + 1 < length && pattern.charAt(i + 1) == '\'') {
624 // '' is treated as escaped '
625 i++;
626 buf.append(c);
627 } else {
628 inLiteral = !inLiteral;
629 }
630 } else if (!inLiteral &&
631 (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
632 i--;
633 break;
634 } else {
635 buf.append(c);
636 }
637 }
638 }
639
640 indexRef[0] = i;
641 return buf.toString();
642 }
643
644 /**
645 * <p>Gets an appropriate rule for the padding required.</p>
646 *
647 * @param field the field to get a rule for
648 * @param padding the padding required
649 * @return a new rule with the correct padding
650 */
651 protected NumberRule selectNumberRule(int field, int padding) {
652 switch (padding) {
653 case 1:
654 return new UnpaddedNumberField(field);
655 case 2:
656 return new TwoDigitNumberField(field);
657 default:
658 return new PaddedNumberField(field, padding);
659 }
367 protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale) {
368 printer= new FastDatePrinter(pattern, timeZone, locale);
369 parser= new FastDateParser(pattern, timeZone, locale);
660370 }
661371
662372 // Format methods
671381 * @return the buffer passed in
672382 */
673383 @Override
674 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
675 if (obj instanceof Date) {
676 return format((Date) obj, toAppendTo);
677 } else if (obj instanceof Calendar) {
678 return format((Calendar) obj, toAppendTo);
679 } else if (obj instanceof Long) {
680 return format(((Long) obj).longValue(), toAppendTo);
681 } else {
682 throw new IllegalArgumentException("Unknown class: " +
683 (obj == null ? "<null>" : obj.getClass().getName()));
684 }
384 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
385 return printer.format(obj, toAppendTo, pos);
685386 }
686387
687388 /**
691392 * @return the formatted string
692393 * @since 2.1
693394 */
694 public String format(long millis) {
695 return format(new Date(millis));
395 @Override
396 public String format(final long millis) {
397 return printer.format(millis);
696398 }
697399
698400 /**
701403 * @param date the date to format
702404 * @return the formatted string
703405 */
704 public String format(Date date) {
705 Calendar c = new GregorianCalendar(mTimeZone, mLocale); // hard code GregorianCalendar
706 c.setTime(date);
707 return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();
406 @Override
407 public String format(final Date date) {
408 return printer.format(date);
708409 }
709410
710411 /**
713414 * @param calendar the calendar to format
714415 * @return the formatted string
715416 */
716 public String format(Calendar calendar) {
717 return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString();
718 }
719
720 /**
721 * <p>Formats a milliseond {@code long} value into the
417 @Override
418 public String format(final Calendar calendar) {
419 return printer.format(calendar);
420 }
421
422 /**
423 * <p>Formats a millisecond {@code long} value into the
722424 * supplied {@code StringBuffer}.</p>
723425 *
724426 * @param millis the millisecond value to format
726428 * @return the specified string buffer
727429 * @since 2.1
728430 */
729 public StringBuffer format(long millis, StringBuffer buf) {
730 return format(new Date(millis), buf);
431 @Override
432 public StringBuffer format(final long millis, final StringBuffer buf) {
433 return printer.format(millis, buf);
731434 }
732435
733436 /**
738441 * @param buf the buffer to format into
739442 * @return the specified string buffer
740443 */
741 public StringBuffer format(Date date, StringBuffer buf) {
742 Calendar c = new GregorianCalendar(mTimeZone, mLocale); // hard code GregorianCalendar
743 c.setTime(date);
744 return applyRules(c, buf);
444 @Override
445 public StringBuffer format(final Date date, final StringBuffer buf) {
446 return printer.format(date, buf);
745447 }
746448
747449 /**
752454 * @param buf the buffer to format into
753455 * @return the specified string buffer
754456 */
755 public StringBuffer format(Calendar calendar, StringBuffer buf) {
756 return applyRules(calendar, buf);
757 }
457 @Override
458 public StringBuffer format(final Calendar calendar, final StringBuffer buf) {
459 return printer.format(calendar, buf);
460 }
461
462 // Parsing
463 //-----------------------------------------------------------------------
464
465
466 /* (non-Javadoc)
467 * @see DateParser#parse(java.lang.String)
468 */
469 @Override
470 public Date parse(final String source) throws ParseException {
471 return parser.parse(source);
472 }
473
474 /* (non-Javadoc)
475 * @see DateParser#parse(java.lang.String, java.text.ParsePosition)
476 */
477 @Override
478 public Date parse(final String source, final ParsePosition pos) {
479 return parser.parse(source, pos);
480 }
481
482 /* (non-Javadoc)
483 * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition)
484 */
485 @Override
486 public Object parseObject(final String source, final ParsePosition pos) {
487 return parser.parseObject(source, pos);
488 }
489
490 // Accessors
491 //-----------------------------------------------------------------------
492 /**
493 * <p>Gets the pattern used by this formatter.</p>
494 *
495 * @return the pattern, {@link java.text.SimpleDateFormat} compatible
496 */
497 @Override
498 public String getPattern() {
499 return printer.getPattern();
500 }
501
502 /**
503 * <p>Gets the time zone used by this formatter.</p>
504 *
505 * <p>This zone is always used for {@code Date} formatting. </p>
506 *
507 * @return the time zone
508 */
509 @Override
510 public TimeZone getTimeZone() {
511 return printer.getTimeZone();
512 }
513
514 /**
515 * <p>Gets the locale used by this formatter.</p>
516 *
517 * @return the locale
518 */
519 @Override
520 public Locale getLocale() {
521 return printer.getLocale();
522 }
523
524 /**
525 * <p>Gets an estimate for the maximum string length that the
526 * formatter will produce.</p>
527 *
528 * <p>The actual formatted length will almost always be less than or
529 * equal to this amount.</p>
530 *
531 * @return the maximum formatted length
532 */
533 public int getMaxLengthEstimate() {
534 return printer.getMaxLengthEstimate();
535 }
536
537 // Basics
538 //-----------------------------------------------------------------------
539 /**
540 * <p>Compares two objects for equality.</p>
541 *
542 * @param obj the object to compare to
543 * @return {@code true} if equal
544 */
545 @Override
546 public boolean equals(final Object obj) {
547 if (obj instanceof FastDateFormat == false) {
548 return false;
549 }
550 final FastDateFormat other = (FastDateFormat) obj;
551 // no need to check parser, as it has same invariants as printer
552 return printer.equals(other.printer);
553 }
554
555 /**
556 * <p>Returns a hashcode compatible with equals.</p>
557 *
558 * @return a hashcode compatible with equals
559 */
560 @Override
561 public int hashCode() {
562 return printer.hashCode();
563 }
564
565 /**
566 * <p>Gets a debugging string version of this formatter.</p>
567 *
568 * @return a debugging string
569 */
570 @Override
571 public String toString() {
572 return "FastDateFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]";
573 }
574
758575
759576 /**
760577 * <p>Performs the formatting by applying the rules to the
764581 * @param buf the buffer to format into
765582 * @return the specified string buffer
766583 */
767 protected StringBuffer applyRules(Calendar calendar, StringBuffer buf) {
768 for (Rule rule : mRules) {
769 rule.appendTo(buf, calendar);
770 }
771 return buf;
772 }
773
774 // Parsing
775 //-----------------------------------------------------------------------
776 /**
777 * <p>Parsing is not supported.</p>
778 *
779 * @param source the string to parse
780 * @param pos the parsing position
781 * @return {@code null} as not supported
782 */
783 @Override
784 public Object parseObject(String source, ParsePosition pos) {
785 pos.setIndex(0);
786 pos.setErrorIndex(0);
787 return null;
788 }
789
790 // Accessors
791 //-----------------------------------------------------------------------
792 /**
793 * <p>Gets the pattern used by this formatter.</p>
794 *
795 * @return the pattern, {@link java.text.SimpleDateFormat} compatible
796 */
797 public String getPattern() {
798 return mPattern;
799 }
800
801 /**
802 * <p>Gets the time zone used by this formatter.</p>
803 *
804 * <p>This zone is always used for {@code Date} formatting. </p>
805 *
806 * @return the time zone
807 */
808 public TimeZone getTimeZone() {
809 return mTimeZone;
810 }
811
812 /**
813 * <p>Gets the locale used by this formatter.</p>
814 *
815 * @return the locale
816 */
817 public Locale getLocale() {
818 return mLocale;
819 }
820
821 /**
822 * <p>Gets an estimate for the maximum string length that the
823 * formatter will produce.</p>
824 *
825 * <p>The actual formatted length will almost always be less than or
826 * equal to this amount.</p>
827 *
828 * @return the maximum formatted length
829 */
830 public int getMaxLengthEstimate() {
831 return mMaxLengthEstimate;
832 }
833
834 // Basics
835 //-----------------------------------------------------------------------
836 /**
837 * <p>Compares two objects for equality.</p>
838 *
839 * @param obj the object to compare to
840 * @return {@code true} if equal
841 */
842 @Override
843 public boolean equals(Object obj) {
844 if (obj instanceof FastDateFormat == false) {
845 return false;
846 }
847 FastDateFormat other = (FastDateFormat) obj;
848 return mPattern.equals(other.mPattern)
849 && mTimeZone.equals(other.mTimeZone)
850 && mLocale.equals(other.mLocale);
851 }
852
853 /**
854 * <p>Returns a hashcode compatible with equals.</p>
855 *
856 * @return a hashcode compatible with equals
857 */
858 @Override
859 public int hashCode() {
860 return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode());
861 }
862
863 /**
864 * <p>Gets a debugging string version of this formatter.</p>
865 *
866 * @return a debugging string
867 */
868 @Override
869 public String toString() {
870 return "FastDateFormat[" + mPattern + "]";
871 }
872
873 // Serializing
874 //-----------------------------------------------------------------------
875 /**
876 * Create the object after serialization. This implementation reinitializes the
877 * transient properties.
878 *
879 * @param in ObjectInputStream from which the object is being deserialized.
880 * @throws IOException if there is an IO issue.
881 * @throws ClassNotFoundException if a class cannot be found.
882 */
883 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
884 in.defaultReadObject();
885 init();
886 }
887
888 // Rules
889 //-----------------------------------------------------------------------
890 /**
891 * <p>Inner class defining a rule.</p>
892 */
893 private interface Rule {
894 /**
895 * Returns the estimated lentgh of the result.
896 *
897 * @return the estimated length
898 */
899 int estimateLength();
900
901 /**
902 * Appends the value of the specified calendar to the output buffer based on the rule implementation.
903 *
904 * @param buffer the output buffer
905 * @param calendar calendar to be appended
906 */
907 void appendTo(StringBuffer buffer, Calendar calendar);
908 }
909
910 /**
911 * <p>Inner class defining a numeric rule.</p>
912 */
913 private interface NumberRule extends Rule {
914 /**
915 * Appends the specified value to the output buffer based on the rule implementation.
916 *
917 * @param buffer the output buffer
918 * @param value the value to be appended
919 */
920 void appendTo(StringBuffer buffer, int value);
921 }
922
923 /**
924 * <p>Inner class to output a constant single character.</p>
925 */
926 private static class CharacterLiteral implements Rule {
927 private final char mValue;
928
929 /**
930 * Constructs a new instance of {@code CharacterLiteral}
931 * to hold the specified value.
932 *
933 * @param value the character literal
934 */
935 CharacterLiteral(char value) {
936 mValue = value;
937 }
938
939 /**
940 * {@inheritDoc}
941 */
942 public int estimateLength() {
943 return 1;
944 }
945
946 /**
947 * {@inheritDoc}
948 */
949 public void appendTo(StringBuffer buffer, Calendar calendar) {
950 buffer.append(mValue);
951 }
952 }
953
954 /**
955 * <p>Inner class to output a constant string.</p>
956 */
957 private static class StringLiteral implements Rule {
958 private final String mValue;
959
960 /**
961 * Constructs a new instance of {@code StringLiteral}
962 * to hold the specified value.
963 *
964 * @param value the string literal
965 */
966 StringLiteral(String value) {
967 mValue = value;
968 }
969
970 /**
971 * {@inheritDoc}
972 */
973 public int estimateLength() {
974 return mValue.length();
975 }
976
977 /**
978 * {@inheritDoc}
979 */
980 public void appendTo(StringBuffer buffer, Calendar calendar) {
981 buffer.append(mValue);
982 }
983 }
984
985 /**
986 * <p>Inner class to output one of a set of values.</p>
987 */
988 private static class TextField implements Rule {
989 private final int mField;
990 private final String[] mValues;
991
992 /**
993 * Constructs an instance of {@code TextField}
994 * with the specified field and values.
995 *
996 * @param field the field
997 * @param values the field values
998 */
999 TextField(int field, String[] values) {
1000 mField = field;
1001 mValues = values;
1002 }
1003
1004 /**
1005 * {@inheritDoc}
1006 */
1007 public int estimateLength() {
1008 int max = 0;
1009 for (int i=mValues.length; --i >= 0; ) {
1010 int len = mValues[i].length();
1011 if (len > max) {
1012 max = len;
1013 }
1014 }
1015 return max;
1016 }
1017
1018 /**
1019 * {@inheritDoc}
1020 */
1021 public void appendTo(StringBuffer buffer, Calendar calendar) {
1022 buffer.append(mValues[calendar.get(mField)]);
1023 }
1024 }
1025
1026 /**
1027 * <p>Inner class to output an unpadded number.</p>
1028 */
1029 private static class UnpaddedNumberField implements NumberRule {
1030 private final int mField;
1031
1032 /**
1033 * Constructs an instance of {@code UnpadedNumberField} with the specified field.
1034 *
1035 * @param field the field
1036 */
1037 UnpaddedNumberField(int field) {
1038 mField = field;
1039 }
1040
1041 /**
1042 * {@inheritDoc}
1043 */
1044 public int estimateLength() {
1045 return 4;
1046 }
1047
1048 /**
1049 * {@inheritDoc}
1050 */
1051 public void appendTo(StringBuffer buffer, Calendar calendar) {
1052 appendTo(buffer, calendar.get(mField));
1053 }
1054
1055 /**
1056 * {@inheritDoc}
1057 */
1058 public final void appendTo(StringBuffer buffer, int value) {
1059 if (value < 10) {
1060 buffer.append((char)(value + '0'));
1061 } else if (value < 100) {
1062 buffer.append((char)(value / 10 + '0'));
1063 buffer.append((char)(value % 10 + '0'));
1064 } else {
1065 buffer.append(Integer.toString(value));
1066 }
1067 }
1068 }
1069
1070 /**
1071 * <p>Inner class to output an unpadded month.</p>
1072 */
1073 private static class UnpaddedMonthField implements NumberRule {
1074 static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField();
1075
1076 /**
1077 * Constructs an instance of {@code UnpaddedMonthField}.
1078 *
1079 */
1080 UnpaddedMonthField() {
1081 super();
1082 }
1083
1084 /**
1085 * {@inheritDoc}
1086 */
1087 public int estimateLength() {
1088 return 2;
1089 }
1090
1091 /**
1092 * {@inheritDoc}
1093 */
1094 public void appendTo(StringBuffer buffer, Calendar calendar) {
1095 appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
1096 }
1097
1098 /**
1099 * {@inheritDoc}
1100 */
1101 public final void appendTo(StringBuffer buffer, int value) {
1102 if (value < 10) {
1103 buffer.append((char)(value + '0'));
1104 } else {
1105 buffer.append((char)(value / 10 + '0'));
1106 buffer.append((char)(value % 10 + '0'));
1107 }
1108 }
1109 }
1110
1111 /**
1112 * <p>Inner class to output a padded number.</p>
1113 */
1114 private static class PaddedNumberField implements NumberRule {
1115 private final int mField;
1116 private final int mSize;
1117
1118 /**
1119 * Constructs an instance of {@code PaddedNumberField}.
1120 *
1121 * @param field the field
1122 * @param size size of the output field
1123 */
1124 PaddedNumberField(int field, int size) {
1125 if (size < 3) {
1126 // Should use UnpaddedNumberField or TwoDigitNumberField.
1127 throw new IllegalArgumentException();
1128 }
1129 mField = field;
1130 mSize = size;
1131 }
1132
1133 /**
1134 * {@inheritDoc}
1135 */
1136 public int estimateLength() {
1137 return 4;
1138 }
1139
1140 /**
1141 * {@inheritDoc}
1142 */
1143 public void appendTo(StringBuffer buffer, Calendar calendar) {
1144 appendTo(buffer, calendar.get(mField));
1145 }
1146
1147 /**
1148 * {@inheritDoc}
1149 */
1150 public final void appendTo(StringBuffer buffer, int value) {
1151 if (value < 100) {
1152 for (int i = mSize; --i >= 2; ) {
1153 buffer.append('0');
1154 }
1155 buffer.append((char)(value / 10 + '0'));
1156 buffer.append((char)(value % 10 + '0'));
1157 } else {
1158 int digits;
1159 if (value < 1000) {
1160 digits = 3;
1161 } else {
1162 Validate.isTrue(value > -1, "Negative values should not be possible", value);
1163 digits = Integer.toString(value).length();
1164 }
1165 for (int i = mSize; --i >= digits; ) {
1166 buffer.append('0');
1167 }
1168 buffer.append(Integer.toString(value));
1169 }
1170 }
1171 }
1172
1173 /**
1174 * <p>Inner class to output a two digit number.</p>
1175 */
1176 private static class TwoDigitNumberField implements NumberRule {
1177 private final int mField;
1178
1179 /**
1180 * Constructs an instance of {@code TwoDigitNumberField} with the specified field.
1181 *
1182 * @param field the field
1183 */
1184 TwoDigitNumberField(int field) {
1185 mField = field;
1186 }
1187
1188 /**
1189 * {@inheritDoc}
1190 */
1191 public int estimateLength() {
1192 return 2;
1193 }
1194
1195 /**
1196 * {@inheritDoc}
1197 */
1198 public void appendTo(StringBuffer buffer, Calendar calendar) {
1199 appendTo(buffer, calendar.get(mField));
1200 }
1201
1202 /**
1203 * {@inheritDoc}
1204 */
1205 public final void appendTo(StringBuffer buffer, int value) {
1206 if (value < 100) {
1207 buffer.append((char)(value / 10 + '0'));
1208 buffer.append((char)(value % 10 + '0'));
1209 } else {
1210 buffer.append(Integer.toString(value));
1211 }
1212 }
1213 }
1214
1215 /**
1216 * <p>Inner class to output a two digit year.</p>
1217 */
1218 private static class TwoDigitYearField implements NumberRule {
1219 static final TwoDigitYearField INSTANCE = new TwoDigitYearField();
1220
1221 /**
1222 * Constructs an instance of {@code TwoDigitYearField}.
1223 */
1224 TwoDigitYearField() {
1225 super();
1226 }
1227
1228 /**
1229 * {@inheritDoc}
1230 */
1231 public int estimateLength() {
1232 return 2;
1233 }
1234
1235 /**
1236 * {@inheritDoc}
1237 */
1238 public void appendTo(StringBuffer buffer, Calendar calendar) {
1239 appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
1240 }
1241
1242 /**
1243 * {@inheritDoc}
1244 */
1245 public final void appendTo(StringBuffer buffer, int value) {
1246 buffer.append((char)(value / 10 + '0'));
1247 buffer.append((char)(value % 10 + '0'));
1248 }
1249 }
1250
1251 /**
1252 * <p>Inner class to output a two digit month.</p>
1253 */
1254 private static class TwoDigitMonthField implements NumberRule {
1255 static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
1256
1257 /**
1258 * Constructs an instance of {@code TwoDigitMonthField}.
1259 */
1260 TwoDigitMonthField() {
1261 super();
1262 }
1263
1264 /**
1265 * {@inheritDoc}
1266 */
1267 public int estimateLength() {
1268 return 2;
1269 }
1270
1271 /**
1272 * {@inheritDoc}
1273 */
1274 public void appendTo(StringBuffer buffer, Calendar calendar) {
1275 appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
1276 }
1277
1278 /**
1279 * {@inheritDoc}
1280 */
1281 public final void appendTo(StringBuffer buffer, int value) {
1282 buffer.append((char)(value / 10 + '0'));
1283 buffer.append((char)(value % 10 + '0'));
1284 }
1285 }
1286
1287 /**
1288 * <p>Inner class to output the twelve hour field.</p>
1289 */
1290 private static class TwelveHourField implements NumberRule {
1291 private final NumberRule mRule;
1292
1293 /**
1294 * Constructs an instance of {@code TwelveHourField} with the specified
1295 * {@code NumberRule}.
1296 *
1297 * @param rule the rule
1298 */
1299 TwelveHourField(NumberRule rule) {
1300 mRule = rule;
1301 }
1302
1303 /**
1304 * {@inheritDoc}
1305 */
1306 public int estimateLength() {
1307 return mRule.estimateLength();
1308 }
1309
1310 /**
1311 * {@inheritDoc}
1312 */
1313 public void appendTo(StringBuffer buffer, Calendar calendar) {
1314 int value = calendar.get(Calendar.HOUR);
1315 if (value == 0) {
1316 value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
1317 }
1318 mRule.appendTo(buffer, value);
1319 }
1320
1321 /**
1322 * {@inheritDoc}
1323 */
1324 public void appendTo(StringBuffer buffer, int value) {
1325 mRule.appendTo(buffer, value);
1326 }
1327 }
1328
1329 /**
1330 * <p>Inner class to output the twenty four hour field.</p>
1331 */
1332 private static class TwentyFourHourField implements NumberRule {
1333 private final NumberRule mRule;
1334
1335 /**
1336 * Constructs an instance of {@code TwentyFourHourField} with the specified
1337 * {@code NumberRule}.
1338 *
1339 * @param rule the rule
1340 */
1341 TwentyFourHourField(NumberRule rule) {
1342 mRule = rule;
1343 }
1344
1345 /**
1346 * {@inheritDoc}
1347 */
1348 public int estimateLength() {
1349 return mRule.estimateLength();
1350 }
1351
1352 /**
1353 * {@inheritDoc}
1354 */
1355 public void appendTo(StringBuffer buffer, Calendar calendar) {
1356 int value = calendar.get(Calendar.HOUR_OF_DAY);
1357 if (value == 0) {
1358 value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
1359 }
1360 mRule.appendTo(buffer, value);
1361 }
1362
1363 /**
1364 * {@inheritDoc}
1365 */
1366 public void appendTo(StringBuffer buffer, int value) {
1367 mRule.appendTo(buffer, value);
1368 }
1369 }
1370
1371 /**
1372 * <p>Inner class to output a time zone name.</p>
1373 */
1374 private static class TimeZoneNameRule implements Rule {
1375 private final TimeZone mTimeZone;
1376 private final String mStandard;
1377 private final String mDaylight;
1378
1379 /**
1380 * Constructs an instance of {@code TimeZoneNameRule} with the specified properties.
1381 *
1382 * @param timeZone the time zone
1383 * @param locale the locale
1384 * @param style the style
1385 */
1386 TimeZoneNameRule(TimeZone timeZone, Locale locale, int style) {
1387 mTimeZone = timeZone;
1388
1389 mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
1390 mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
1391 }
1392
1393 /**
1394 * {@inheritDoc}
1395 */
1396 public int estimateLength() {
1397 return Math.max(mStandard.length(), mDaylight.length());
1398 }
1399
1400 /**
1401 * {@inheritDoc}
1402 */
1403 public void appendTo(StringBuffer buffer, Calendar calendar) {
1404 if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
1405 buffer.append(mDaylight);
1406 } else {
1407 buffer.append(mStandard);
1408 }
1409 }
1410 }
1411
1412 /**
1413 * <p>Inner class to output a time zone as a number {@code +/-HHMM}
1414 * or {@code +/-HH:MM}.</p>
1415 */
1416 private static class TimeZoneNumberRule implements Rule {
1417 static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true);
1418 static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false);
1419
1420 final boolean mColon;
1421
1422 /**
1423 * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties.
1424 *
1425 * @param colon add colon between HH and MM in the output if {@code true}
1426 */
1427 TimeZoneNumberRule(boolean colon) {
1428 mColon = colon;
1429 }
1430
1431 /**
1432 * {@inheritDoc}
1433 */
1434 public int estimateLength() {
1435 return 5;
1436 }
1437
1438 /**
1439 * {@inheritDoc}
1440 */
1441 public void appendTo(StringBuffer buffer, Calendar calendar) {
1442 int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
1443
1444 if (offset < 0) {
1445 buffer.append('-');
1446 offset = -offset;
1447 } else {
1448 buffer.append('+');
1449 }
1450
1451 int hours = offset / (60 * 60 * 1000);
1452 buffer.append((char)(hours / 10 + '0'));
1453 buffer.append((char)(hours % 10 + '0'));
1454
1455 if (mColon) {
1456 buffer.append(':');
1457 }
1458
1459 int minutes = offset / (60 * 1000) - 60 * hours;
1460 buffer.append((char)(minutes / 10 + '0'));
1461 buffer.append((char)(minutes % 10 + '0'));
1462 }
1463 }
1464
1465 // ----------------------------------------------------------------------
1466 /**
1467 * <p>Inner class that acts as a compound key for time zone names.</p>
1468 */
1469 private static class TimeZoneDisplayKey {
1470 private final TimeZone mTimeZone;
1471 private final int mStyle;
1472 private final Locale mLocale;
1473
1474 /**
1475 * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties.
1476 *
1477 * @param timeZone the time zone
1478 * @param daylight adjust the style for daylight saving time if {@code true}
1479 * @param style the timezone style
1480 * @param locale the timezone locale
1481 */
1482 TimeZoneDisplayKey(TimeZone timeZone,
1483 boolean daylight, int style, Locale locale) {
1484 mTimeZone = timeZone;
1485 if (daylight) {
1486 style |= 0x80000000;
1487 }
1488 mStyle = style;
1489 mLocale = locale;
1490 }
1491
1492 /**
1493 * {@inheritDoc}
1494 */
1495 @Override
1496 public int hashCode() {
1497 return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode();
1498 }
1499
1500 /**
1501 * {@inheritDoc}
1502 */
1503 @Override
1504 public boolean equals(Object obj) {
1505 if (this == obj) {
1506 return true;
1507 }
1508 if (obj instanceof TimeZoneDisplayKey) {
1509 TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
1510 return
1511 mTimeZone.equals(other.mTimeZone) &&
1512 mStyle == other.mStyle &&
1513 mLocale.equals(other.mLocale);
1514 }
1515 return false;
1516 }
1517 }
584 protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) {
585 return printer.applyRules(calendar, buf);
586 }
587
588
1518589 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import java.io.IOException;
19 import java.io.ObjectInputStream;
20 import java.io.Serializable;
21 import java.text.DateFormatSymbols;
22 import java.text.ParseException;
23 import java.text.ParsePosition;
24 import java.util.ArrayList;
25 import java.util.Calendar;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.Map;
30 import java.util.SortedMap;
31 import java.util.TimeZone;
32 import java.util.TreeMap;
33 import java.util.concurrent.ConcurrentHashMap;
34 import java.util.concurrent.ConcurrentMap;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37
38 /**
39 * <p>FastDateParser is a fast and thread-safe version of
40 * {@link java.text.SimpleDateFormat}.</p>
41 *
42 * <p>This class can be used as a direct replacement for
43 * <code>SimpleDateFormat</code> in most parsing situations.
44 * This class is especially useful in multi-threaded server environments.
45 * <code>SimpleDateFormat</code> is not thread-safe in any JDK version,
46 * nor will it be as Sun have closed the
47 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4228335">bug</a>/RFE.
48 * </p>
49 *
50 * <p>Only parsing is supported, but all patterns are compatible with
51 * SimpleDateFormat.</p>
52 *
53 * <p>Timing tests indicate this class is as about as fast as SimpleDateFormat
54 * in single thread applications and about 25% faster in multi-thread applications.</p>
55 *
56 * <p>Note that the code only handles Gregorian calendars. The following non-Gregorian
57 * calendars use SimpleDateFormat internally, and so will be slower:
58 * <ul>
59 * <li>ja_JP_TH - Japanese Imperial</li>
60 * <li>th_TH (any variant) - Thai Buddhist</li>
61 * </ul>
62 * </p>
63 *
64 * @version $Id: FastDateParser.java 1555485 2014-01-05 12:08:29Z britter $
65 * @since 3.2
66 */
67 public class FastDateParser implements DateParser, Serializable {
68 /**
69 * Required for serialization support.
70 *
71 * @see java.io.Serializable
72 */
73 private static final long serialVersionUID = 1L;
74
75 static final Locale JAPANESE_IMPERIAL = new Locale("ja","JP","JP");
76
77 // defining fields
78 private final String pattern;
79 private final TimeZone timeZone;
80 private final Locale locale;
81
82 // derived fields
83 private transient Pattern parsePattern;
84 private transient Strategy[] strategies;
85 private transient int thisYear;
86
87 // dynamic fields to communicate with Strategy
88 private transient String currentFormatField;
89 private transient Strategy nextStrategy;
90
91 /**
92 * <p>Constructs a new FastDateParser.</p>
93 *
94 * @param pattern non-null {@link java.text.SimpleDateFormat} compatible
95 * pattern
96 * @param timeZone non-null time zone to use
97 * @param locale non-null locale
98 */
99 protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) {
100 this.pattern = pattern;
101 this.timeZone = timeZone;
102 this.locale = locale;
103 init();
104 }
105
106 /**
107 * Initialize derived fields from defining fields.
108 * This is called from constructor and from readObject (de-serialization)
109 */
110 private void init() {
111 final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
112 thisYear= definingCalendar.get(Calendar.YEAR);
113
114 final StringBuilder regex= new StringBuilder();
115 final List<Strategy> collector = new ArrayList<Strategy>();
116
117 final Matcher patternMatcher= formatPattern.matcher(pattern);
118 if(!patternMatcher.lookingAt()) {
119 throw new IllegalArgumentException(
120 "Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
121 }
122
123 currentFormatField= patternMatcher.group();
124 Strategy currentStrategy= getStrategy(currentFormatField, definingCalendar);
125 for(;;) {
126 patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
127 if(!patternMatcher.lookingAt()) {
128 nextStrategy = null;
129 break;
130 }
131 final String nextFormatField= patternMatcher.group();
132 nextStrategy = getStrategy(nextFormatField, definingCalendar);
133 if(currentStrategy.addRegex(this, regex)) {
134 collector.add(currentStrategy);
135 }
136 currentFormatField= nextFormatField;
137 currentStrategy= nextStrategy;
138 }
139 if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
140 throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart());
141 }
142 if(currentStrategy.addRegex(this, regex)) {
143 collector.add(currentStrategy);
144 }
145 currentFormatField= null;
146 strategies= collector.toArray(new Strategy[collector.size()]);
147 parsePattern= Pattern.compile(regex.toString());
148 }
149
150 // Accessors
151 //-----------------------------------------------------------------------
152 /* (non-Javadoc)
153 * @see org.apache.commons.lang3.time.DateParser#getPattern()
154 */
155 @Override
156 public String getPattern() {
157 return pattern;
158 }
159
160 /* (non-Javadoc)
161 * @see org.apache.commons.lang3.time.DateParser#getTimeZone()
162 */
163 @Override
164 public TimeZone getTimeZone() {
165 return timeZone;
166 }
167
168 /* (non-Javadoc)
169 * @see org.apache.commons.lang3.time.DateParser#getLocale()
170 */
171 @Override
172 public Locale getLocale() {
173 return locale;
174 }
175
176 /**
177 * Returns the generated pattern (for testing purposes).
178 *
179 * @return the generated pattern
180 */
181 Pattern getParsePattern() {
182 return parsePattern;
183 }
184
185 // Basics
186 //-----------------------------------------------------------------------
187 /**
188 * <p>Compare another object for equality with this object.</p>
189 *
190 * @param obj the object to compare to
191 * @return <code>true</code>if equal to this instance
192 */
193 @Override
194 public boolean equals(final Object obj) {
195 if (! (obj instanceof FastDateParser) ) {
196 return false;
197 }
198 final FastDateParser other = (FastDateParser) obj;
199 return pattern.equals(other.pattern)
200 && timeZone.equals(other.timeZone)
201 && locale.equals(other.locale);
202 }
203
204 /**
205 * <p>Return a hashcode compatible with equals.</p>
206 *
207 * @return a hashcode compatible with equals
208 */
209 @Override
210 public int hashCode() {
211 return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode());
212 }
213
214 /**
215 * <p>Get a string version of this formatter.</p>
216 *
217 * @return a debugging string
218 */
219 @Override
220 public String toString() {
221 return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]";
222 }
223
224 // Serializing
225 //-----------------------------------------------------------------------
226 /**
227 * Create the object after serialization. This implementation reinitializes the
228 * transient properties.
229 *
230 * @param in ObjectInputStream from which the object is being deserialized.
231 * @throws IOException if there is an IO issue.
232 * @throws ClassNotFoundException if a class cannot be found.
233 */
234 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
235 in.defaultReadObject();
236 init();
237 }
238
239 /* (non-Javadoc)
240 * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String)
241 */
242 @Override
243 public Object parseObject(final String source) throws ParseException {
244 return parse(source);
245 }
246
247 /* (non-Javadoc)
248 * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String)
249 */
250 @Override
251 public Date parse(final String source) throws ParseException {
252 final Date date= parse(source, new ParsePosition(0));
253 if(date==null) {
254 // Add a note re supported date range
255 if (locale.equals(JAPANESE_IMPERIAL)) {
256 throw new ParseException(
257 "(The " +locale + " locale does not support dates before 1868 AD)\n" +
258 "Unparseable date: \""+source+"\" does not match "+parsePattern.pattern(), 0);
259 }
260 throw new ParseException("Unparseable date: \""+source+"\" does not match "+parsePattern.pattern(), 0);
261 }
262 return date;
263 }
264
265 /* (non-Javadoc)
266 * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, java.text.ParsePosition)
267 */
268 @Override
269 public Object parseObject(final String source, final ParsePosition pos) {
270 return parse(source, pos);
271 }
272
273 /* (non-Javadoc)
274 * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition)
275 */
276 @Override
277 public Date parse(final String source, final ParsePosition pos) {
278 final int offset= pos.getIndex();
279 final Matcher matcher= parsePattern.matcher(source.substring(offset));
280 if(!matcher.lookingAt()) {
281 return null;
282 }
283 // timing tests indicate getting new instance is 19% faster than cloning
284 final Calendar cal= Calendar.getInstance(timeZone, locale);
285 cal.clear();
286
287 for(int i=0; i<strategies.length;) {
288 final Strategy strategy= strategies[i++];
289 strategy.setCalendar(this, cal, matcher.group(i));
290 }
291 pos.setIndex(offset+matcher.end());
292 return cal.getTime();
293 }
294
295 // Support for strategies
296 //-----------------------------------------------------------------------
297
298 /**
299 * Escape constant fields into regular expression
300 * @param regex The destination regex
301 * @param value The source field
302 * @param unquote If true, replace two success quotes ('') with single quote (')
303 * @return The <code>StringBuilder</code>
304 */
305 private static StringBuilder escapeRegex(final StringBuilder regex, final String value, final boolean unquote) {
306 regex.append("\\Q");
307 for(int i= 0; i<value.length(); ++i) {
308 char c= value.charAt(i);
309 switch(c) {
310 case '\'':
311 if(unquote) {
312 if(++i==value.length()) {
313 return regex;
314 }
315 c= value.charAt(i);
316 }
317 break;
318 case '\\':
319 if(++i==value.length()) {
320 break;
321 }
322 /*
323 * If we have found \E, we replace it with \E\\E\Q, i.e. we stop the quoting,
324 * quote the \ in \E, then restart the quoting.
325 *
326 * Otherwise we just output the two characters.
327 * In each case the initial \ needs to be output and the final char is done at the end
328 */
329 regex.append(c); // we always want the original \
330 c = value.charAt(i); // Is it followed by E ?
331 if (c == 'E') { // \E detected
332 regex.append("E\\\\E\\"); // see comment above
333 c = 'Q'; // appended below
334 }
335 break;
336 }
337 regex.append(c);
338 }
339 regex.append("\\E");
340 return regex;
341 }
342
343
344 /**
345 * Get the short and long values displayed for a field
346 * @param field The field of interest
347 * @param definingCalendar The calendar to obtain the short and long values
348 * @param locale The locale of display names
349 * @return A Map of the field key / value pairs
350 */
351 private static Map<String, Integer> getDisplayNames(final int field, final Calendar definingCalendar, final Locale locale) {
352 return definingCalendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
353 }
354
355 /**
356 * Adjust dates to be within 80 years before and 20 years after instantiation
357 * @param twoDigitYear The year to adjust
358 * @return A value within -80 and +20 years from instantiation of this instance
359 */
360 int adjustYear(final int twoDigitYear) {
361 final int trial= twoDigitYear + thisYear - thisYear%100;
362 if(trial < thisYear+20) {
363 return trial;
364 }
365 return trial-100;
366 }
367
368 /**
369 * Is the next field a number?
370 * @return true, if next field will be a number
371 */
372 boolean isNextNumber() {
373 return nextStrategy!=null && nextStrategy.isNumber();
374 }
375
376 /**
377 * What is the width of the current field?
378 * @return The number of characters in the current format field
379 */
380 int getFieldWidth() {
381 return currentFormatField.length();
382 }
383
384 /**
385 * A strategy to parse a single field from the parsing pattern
386 */
387 private static abstract class Strategy {
388 /**
389 * Is this field a number?
390 * The default implementation returns false.
391 *
392 * @return true, if field is a number
393 */
394 boolean isNumber() {
395 return false;
396 }
397 /**
398 * Set the Calendar with the parsed field.
399 *
400 * The default implementation does nothing.
401 *
402 * @param parser The parser calling this strategy
403 * @param cal The <code>Calendar</code> to set
404 * @param value The parsed field to translate and set in cal
405 */
406 void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
407
408 }
409 /**
410 * Generate a <code>Pattern</code> regular expression to the <code>StringBuilder</code>
411 * which will accept this field
412 * @param parser The parser calling this strategy
413 * @param regex The <code>StringBuilder</code> to append to
414 * @return true, if this field will set the calendar;
415 * false, if this field is a constant value
416 */
417 abstract boolean addRegex(FastDateParser parser, StringBuilder regex);
418 }
419
420 /**
421 * A <code>Pattern</code> to parse the user supplied SimpleDateFormat pattern
422 */
423 private static final Pattern formatPattern= Pattern.compile(
424 "D+|E+|F+|G+|H+|K+|M+|S+|W+|Z+|a+|d+|h+|k+|m+|s+|w+|y+|z+|''|'[^']++(''[^']*+)*+'|[^'A-Za-z]++");
425
426 /**
427 * Obtain a Strategy given a field from a SimpleDateFormat pattern
428 * @param formatField A sub-sequence of the SimpleDateFormat pattern
429 * @param definingCalendar The calendar to obtain the short and long values
430 * @return The Strategy that will handle parsing for the field
431 */
432 private Strategy getStrategy(String formatField, final Calendar definingCalendar) {
433 switch(formatField.charAt(0)) {
434 case '\'':
435 if(formatField.length()>2) {
436 formatField= formatField.substring(1, formatField.length()-1);
437 }
438 //$FALL-THROUGH$
439 default:
440 return new CopyQuotedStrategy(formatField);
441 case 'D':
442 return DAY_OF_YEAR_STRATEGY;
443 case 'E':
444 return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar);
445 case 'F':
446 return DAY_OF_WEEK_IN_MONTH_STRATEGY;
447 case 'G':
448 return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar);
449 case 'H':
450 return MODULO_HOUR_OF_DAY_STRATEGY;
451 case 'K':
452 return HOUR_STRATEGY;
453 case 'M':
454 return formatField.length()>=3 ?getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) :NUMBER_MONTH_STRATEGY;
455 case 'S':
456 return MILLISECOND_STRATEGY;
457 case 'W':
458 return WEEK_OF_MONTH_STRATEGY;
459 case 'a':
460 return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar);
461 case 'd':
462 return DAY_OF_MONTH_STRATEGY;
463 case 'h':
464 return MODULO_HOUR_STRATEGY;
465 case 'k':
466 return HOUR_OF_DAY_STRATEGY;
467 case 'm':
468 return MINUTE_STRATEGY;
469 case 's':
470 return SECOND_STRATEGY;
471 case 'w':
472 return WEEK_OF_YEAR_STRATEGY;
473 case 'y':
474 return formatField.length()>2 ?LITERAL_YEAR_STRATEGY :ABBREVIATED_YEAR_STRATEGY;
475 case 'Z':
476 case 'z':
477 return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar);
478 }
479 }
480
481 @SuppressWarnings("unchecked") // OK because we are creating an array with no entries
482 private static ConcurrentMap<Locale, Strategy>[] caches = new ConcurrentMap[Calendar.FIELD_COUNT];
483
484 /**
485 * Get a cache of Strategies for a particular field
486 * @param field The Calendar field
487 * @return a cache of Locale to Strategy
488 */
489 private static ConcurrentMap<Locale, Strategy> getCache(final int field) {
490 synchronized(caches) {
491 if(caches[field]==null) {
492 caches[field]= new ConcurrentHashMap<Locale,Strategy>(3);
493 }
494 return caches[field];
495 }
496 }
497
498 /**
499 * Construct a Strategy that parses a Text field
500 * @param field The Calendar field
501 * @param definingCalendar The calendar to obtain the short and long values
502 * @return a TextStrategy for the field and Locale
503 */
504 private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) {
505 final ConcurrentMap<Locale,Strategy> cache = getCache(field);
506 Strategy strategy= cache.get(locale);
507 if(strategy==null) {
508 strategy= field==Calendar.ZONE_OFFSET
509 ? new TimeZoneStrategy(locale)
510 : new TextStrategy(field, definingCalendar, locale);
511 final Strategy inCache= cache.putIfAbsent(locale, strategy);
512 if(inCache!=null) {
513 return inCache;
514 }
515 }
516 return strategy;
517 }
518
519 /**
520 * A strategy that copies the static or quoted field in the parsing pattern
521 */
522 private static class CopyQuotedStrategy extends Strategy {
523 private final String formatField;
524
525 /**
526 * Construct a Strategy that ensures the formatField has literal text
527 * @param formatField The literal text to match
528 */
529 CopyQuotedStrategy(final String formatField) {
530 this.formatField= formatField;
531 }
532
533 /**
534 * {@inheritDoc}
535 */
536 @Override
537 boolean isNumber() {
538 char c= formatField.charAt(0);
539 if(c=='\'') {
540 c= formatField.charAt(1);
541 }
542 return Character.isDigit(c);
543 }
544
545 /**
546 * {@inheritDoc}
547 */
548 @Override
549 boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
550 escapeRegex(regex, formatField, true);
551 return false;
552 }
553 }
554
555 /**
556 * A strategy that handles a text field in the parsing pattern
557 */
558 private static class TextStrategy extends Strategy {
559 private final int field;
560 private final Map<String, Integer> keyValues;
561
562 /**
563 * Construct a Strategy that parses a Text field
564 * @param field The Calendar field
565 * @param definingCalendar The Calendar to use
566 * @param locale The Locale to use
567 */
568 TextStrategy(final int field, final Calendar definingCalendar, final Locale locale) {
569 this.field= field;
570 this.keyValues= getDisplayNames(field, definingCalendar, locale);
571 }
572
573 /**
574 * {@inheritDoc}
575 */
576 @Override
577 boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
578 regex.append('(');
579 for(final String textKeyValue : keyValues.keySet()) {
580 escapeRegex(regex, textKeyValue, false).append('|');
581 }
582 regex.setCharAt(regex.length()-1, ')');
583 return true;
584 }
585
586 /**
587 * {@inheritDoc}
588 */
589 @Override
590 void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
591 final Integer iVal = keyValues.get(value);
592 if(iVal == null) {
593 final StringBuilder sb= new StringBuilder(value);
594 sb.append(" not in (");
595 for(final String textKeyValue : keyValues.keySet()) {
596 sb.append(textKeyValue).append(' ');
597 }
598 sb.setCharAt(sb.length()-1, ')');
599 throw new IllegalArgumentException(sb.toString());
600 }
601 cal.set(field, iVal.intValue());
602 }
603 }
604
605
606 /**
607 * A strategy that handles a number field in the parsing pattern
608 */
609 private static class NumberStrategy extends Strategy {
610 private final int field;
611
612 /**
613 * Construct a Strategy that parses a Number field
614 * @param field The Calendar field
615 */
616 NumberStrategy(final int field) {
617 this.field= field;
618 }
619
620 /**
621 * {@inheritDoc}
622 */
623 @Override
624 boolean isNumber() {
625 return true;
626 }
627
628 /**
629 * {@inheritDoc}
630 */
631 @Override
632 boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
633 if(parser.isNextNumber()) {
634 regex.append("(\\p{IsNd}{").append(parser.getFieldWidth()).append("}+)");
635 }
636 else {
637 regex.append("(\\p{IsNd}++)");
638 }
639 return true;
640 }
641
642 /**
643 * {@inheritDoc}
644 */
645 @Override
646 void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
647 cal.set(field, modify(Integer.parseInt(value)));
648 }
649
650 /**
651 * Make any modifications to parsed integer
652 * @param iValue The parsed integer
653 * @return The modified value
654 */
655 int modify(final int iValue) {
656 return iValue;
657 }
658 }
659
660 private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) {
661 /**
662 * {@inheritDoc}
663 */
664 @Override
665 void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
666 int iValue= Integer.parseInt(value);
667 if(iValue<100) {
668 iValue= parser.adjustYear(iValue);
669 }
670 cal.set(Calendar.YEAR, iValue);
671 }
672 };
673
674 /**
675 * A strategy that handles a timezone field in the parsing pattern
676 */
677 private static class TimeZoneStrategy extends Strategy {
678
679 private final String validTimeZoneChars;
680 private final SortedMap<String, TimeZone> tzNames= new TreeMap<String, TimeZone>(String.CASE_INSENSITIVE_ORDER);
681
682 /**
683 * Index of zone id
684 */
685 private static final int ID = 0;
686 /**
687 * Index of the long name of zone in standard time
688 */
689 private static final int LONG_STD = 1;
690 /**
691 * Index of the short name of zone in standard time
692 */
693 private static final int SHORT_STD = 2;
694 /**
695 * Index of the long name of zone in daylight saving time
696 */
697 private static final int LONG_DST = 3;
698 /**
699 * Index of the short name of zone in daylight saving time
700 */
701 private static final int SHORT_DST = 4;
702
703 /**
704 * Construct a Strategy that parses a TimeZone
705 * @param locale The Locale
706 */
707 TimeZoneStrategy(final Locale locale) {
708 final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings();
709 for (String[] zone : zones) {
710 if (zone[ID].startsWith("GMT")) {
711 continue;
712 }
713 final TimeZone tz = TimeZone.getTimeZone(zone[ID]);
714 if (!tzNames.containsKey(zone[LONG_STD])){
715 tzNames.put(zone[LONG_STD], tz);
716 }
717 if (!tzNames.containsKey(zone[SHORT_STD])){
718 tzNames.put(zone[SHORT_STD], tz);
719 }
720 if (tz.useDaylightTime()) {
721 if (!tzNames.containsKey(zone[LONG_DST])){
722 tzNames.put(zone[LONG_DST], tz);
723 }
724 if (!tzNames.containsKey(zone[SHORT_DST])){
725 tzNames.put(zone[SHORT_DST], tz);
726 }
727 }
728 }
729
730 final StringBuilder sb= new StringBuilder();
731 sb.append("(GMT[+\\-]\\d{0,1}\\d{2}|[+\\-]\\d{2}:?\\d{2}|");
732 for(final String id : tzNames.keySet()) {
733 escapeRegex(sb, id, false).append('|');
734 }
735 sb.setCharAt(sb.length()-1, ')');
736 validTimeZoneChars= sb.toString();
737 }
738
739 /**
740 * {@inheritDoc}
741 */
742 @Override
743 boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
744 regex.append(validTimeZoneChars);
745 return true;
746 }
747
748 /**
749 * {@inheritDoc}
750 */
751 @Override
752 void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
753 TimeZone tz;
754 if(value.charAt(0)=='+' || value.charAt(0)=='-') {
755 tz= TimeZone.getTimeZone("GMT"+value);
756 }
757 else if(value.startsWith("GMT")) {
758 tz= TimeZone.getTimeZone(value);
759 }
760 else {
761 tz= tzNames.get(value);
762 if(tz==null) {
763 throw new IllegalArgumentException(value + " is not a supported timezone name");
764 }
765 }
766 cal.setTimeZone(tz);
767 }
768 }
769
770 private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) {
771 @Override
772 int modify(final int iValue) {
773 return iValue-1;
774 }
775 };
776 private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR);
777 private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR);
778 private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH);
779 private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR);
780 private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH);
781 private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH);
782 private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY);
783 private static final Strategy MODULO_HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) {
784 @Override
785 int modify(final int iValue) {
786 return iValue%24;
787 }
788 };
789 private static final Strategy MODULO_HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR) {
790 @Override
791 int modify(final int iValue) {
792 return iValue%12;
793 }
794 };
795 private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR);
796 private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE);
797 private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND);
798 private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND);
799 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import java.io.IOException;
19 import java.io.ObjectInputStream;
20 import java.io.Serializable;
21 import java.text.DateFormat;
22 import java.text.DateFormatSymbols;
23 import java.text.FieldPosition;
24 import java.util.ArrayList;
25 import java.util.Calendar;
26 import java.util.Date;
27 import java.util.GregorianCalendar;
28 import java.util.List;
29 import java.util.Locale;
30 import java.util.TimeZone;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentMap;
33
34 import org.apache.commons.lang3.Validate;
35
36 /**
37 * <p>FastDatePrinter is a fast and thread-safe version of
38 * {@link java.text.SimpleDateFormat}.</p>
39 *
40 * <p>This class can be used as a direct replacement to
41 * {@code SimpleDateFormat} in most formatting situations.
42 * This class is especially useful in multi-threaded server environments.
43 * {@code SimpleDateFormat} is not thread-safe in any JDK version,
44 * nor will it be as Sun have closed the bug/RFE.
45 * </p>
46 *
47 * <p>Only formatting is supported, but all patterns are compatible with
48 * SimpleDateFormat (except time zones and some year patterns - see below).</p>
49 *
50 * <p>Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent
51 * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}).
52 * This pattern letter can be used here (on all JDK versions).</p>
53 *
54 * <p>In addition, the pattern {@code 'ZZ'} has been made to represent
55 * ISO8601 full format time zones (eg. {@code +08:00} or {@code -11:00}).
56 * This introduces a minor incompatibility with Java 1.4, but at a gain of
57 * useful functionality.</p>
58 *
59 * <p>Javadoc cites for the year pattern: <i>For formatting, if the number of
60 * pattern letters is 2, the year is truncated to 2 digits; otherwise it is
61 * interpreted as a number.</i> Starting with Java 1.7 a pattern of 'Y' or
62 * 'YYY' will be formatted as '2003', while it was '03' in former Java
63 * versions. FastDatePrinter implements the behavior of Java 7.</p>
64 *
65 * @version $Id: FastDatePrinter.java 1552661 2013-12-20 13:36:30Z britter $
66 * @since 3.2
67 */
68 public class FastDatePrinter implements DatePrinter, Serializable {
69 // A lot of the speed in this class comes from caching, but some comes
70 // from the special int to StringBuffer conversion.
71 //
72 // The following produces a padded 2 digit number:
73 // buffer.append((char)(value / 10 + '0'));
74 // buffer.append((char)(value % 10 + '0'));
75 //
76 // Note that the fastest append to StringBuffer is a single char (used here).
77 // Note that Integer.toString() is not called, the conversion is simply
78 // taking the value and adding (mathematically) the ASCII value for '0'.
79 // So, don't change this code! It works and is very fast.
80
81 /**
82 * Required for serialization support.
83 *
84 * @see java.io.Serializable
85 */
86 private static final long serialVersionUID = 1L;
87
88 /**
89 * FULL locale dependent date or time style.
90 */
91 public static final int FULL = DateFormat.FULL;
92 /**
93 * LONG locale dependent date or time style.
94 */
95 public static final int LONG = DateFormat.LONG;
96 /**
97 * MEDIUM locale dependent date or time style.
98 */
99 public static final int MEDIUM = DateFormat.MEDIUM;
100 /**
101 * SHORT locale dependent date or time style.
102 */
103 public static final int SHORT = DateFormat.SHORT;
104
105 /**
106 * The pattern.
107 */
108 private final String mPattern;
109 /**
110 * The time zone.
111 */
112 private final TimeZone mTimeZone;
113 /**
114 * The locale.
115 */
116 private final Locale mLocale;
117 /**
118 * The parsed rules.
119 */
120 private transient Rule[] mRules;
121 /**
122 * The estimated maximum length.
123 */
124 private transient int mMaxLengthEstimate;
125
126 // Constructor
127 //-----------------------------------------------------------------------
128 /**
129 * <p>Constructs a new FastDatePrinter.</p>
130 *
131 * @param pattern {@link java.text.SimpleDateFormat} compatible pattern
132 * @param timeZone non-null time zone to use
133 * @param locale non-null locale to use
134 * @throws NullPointerException if pattern, timeZone, or locale is null.
135 */
136 protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) {
137 mPattern = pattern;
138 mTimeZone = timeZone;
139 mLocale = locale;
140
141 init();
142 }
143
144 /**
145 * <p>Initializes the instance for first use.</p>
146 */
147 private void init() {
148 final List<Rule> rulesList = parsePattern();
149 mRules = rulesList.toArray(new Rule[rulesList.size()]);
150
151 int len = 0;
152 for (int i=mRules.length; --i >= 0; ) {
153 len += mRules[i].estimateLength();
154 }
155
156 mMaxLengthEstimate = len;
157 }
158
159 // Parse the pattern
160 //-----------------------------------------------------------------------
161 /**
162 * <p>Returns a list of Rules given a pattern.</p>
163 *
164 * @return a {@code List} of Rule objects
165 * @throws IllegalArgumentException if pattern is invalid
166 */
167 protected List<Rule> parsePattern() {
168 final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
169 final List<Rule> rules = new ArrayList<Rule>();
170
171 final String[] ERAs = symbols.getEras();
172 final String[] months = symbols.getMonths();
173 final String[] shortMonths = symbols.getShortMonths();
174 final String[] weekdays = symbols.getWeekdays();
175 final String[] shortWeekdays = symbols.getShortWeekdays();
176 final String[] AmPmStrings = symbols.getAmPmStrings();
177
178 final int length = mPattern.length();
179 final int[] indexRef = new int[1];
180
181 for (int i = 0; i < length; i++) {
182 indexRef[0] = i;
183 final String token = parseToken(mPattern, indexRef);
184 i = indexRef[0];
185
186 final int tokenLen = token.length();
187 if (tokenLen == 0) {
188 break;
189 }
190
191 Rule rule;
192 final char c = token.charAt(0);
193
194 switch (c) {
195 case 'G': // era designator (text)
196 rule = new TextField(Calendar.ERA, ERAs);
197 break;
198 case 'y': // year (number)
199 if (tokenLen == 2) {
200 rule = TwoDigitYearField.INSTANCE;
201 } else {
202 rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
203 }
204 break;
205 case 'M': // month in year (text and number)
206 if (tokenLen >= 4) {
207 rule = new TextField(Calendar.MONTH, months);
208 } else if (tokenLen == 3) {
209 rule = new TextField(Calendar.MONTH, shortMonths);
210 } else if (tokenLen == 2) {
211 rule = TwoDigitMonthField.INSTANCE;
212 } else {
213 rule = UnpaddedMonthField.INSTANCE;
214 }
215 break;
216 case 'd': // day in month (number)
217 rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
218 break;
219 case 'h': // hour in am/pm (number, 1..12)
220 rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
221 break;
222 case 'H': // hour in day (number, 0..23)
223 rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
224 break;
225 case 'm': // minute in hour (number)
226 rule = selectNumberRule(Calendar.MINUTE, tokenLen);
227 break;
228 case 's': // second in minute (number)
229 rule = selectNumberRule(Calendar.SECOND, tokenLen);
230 break;
231 case 'S': // millisecond (number)
232 rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
233 break;
234 case 'E': // day in week (text)
235 rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
236 break;
237 case 'D': // day in year (number)
238 rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
239 break;
240 case 'F': // day of week in month (number)
241 rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
242 break;
243 case 'w': // week in year (number)
244 rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
245 break;
246 case 'W': // week in month (number)
247 rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
248 break;
249 case 'a': // am/pm marker (text)
250 rule = new TextField(Calendar.AM_PM, AmPmStrings);
251 break;
252 case 'k': // hour in day (1..24)
253 rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
254 break;
255 case 'K': // hour in am/pm (0..11)
256 rule = selectNumberRule(Calendar.HOUR, tokenLen);
257 break;
258 case 'z': // time zone (text)
259 if (tokenLen >= 4) {
260 rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
261 } else {
262 rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
263 }
264 break;
265 case 'Z': // time zone (value)
266 if (tokenLen == 1) {
267 rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
268 } else {
269 rule = TimeZoneNumberRule.INSTANCE_COLON;
270 }
271 break;
272 case '\'': // literal text
273 final String sub = token.substring(1);
274 if (sub.length() == 1) {
275 rule = new CharacterLiteral(sub.charAt(0));
276 } else {
277 rule = new StringLiteral(sub);
278 }
279 break;
280 default:
281 throw new IllegalArgumentException("Illegal pattern component: " + token);
282 }
283
284 rules.add(rule);
285 }
286
287 return rules;
288 }
289
290 /**
291 * <p>Performs the parsing of tokens.</p>
292 *
293 * @param pattern the pattern
294 * @param indexRef index references
295 * @return parsed token
296 */
297 protected String parseToken(final String pattern, final int[] indexRef) {
298 final StringBuilder buf = new StringBuilder();
299
300 int i = indexRef[0];
301 final int length = pattern.length();
302
303 char c = pattern.charAt(i);
304 if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
305 // Scan a run of the same character, which indicates a time
306 // pattern.
307 buf.append(c);
308
309 while (i + 1 < length) {
310 final char peek = pattern.charAt(i + 1);
311 if (peek == c) {
312 buf.append(c);
313 i++;
314 } else {
315 break;
316 }
317 }
318 } else {
319 // This will identify token as text.
320 buf.append('\'');
321
322 boolean inLiteral = false;
323
324 for (; i < length; i++) {
325 c = pattern.charAt(i);
326
327 if (c == '\'') {
328 if (i + 1 < length && pattern.charAt(i + 1) == '\'') {
329 // '' is treated as escaped '
330 i++;
331 buf.append(c);
332 } else {
333 inLiteral = !inLiteral;
334 }
335 } else if (!inLiteral &&
336 (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
337 i--;
338 break;
339 } else {
340 buf.append(c);
341 }
342 }
343 }
344
345 indexRef[0] = i;
346 return buf.toString();
347 }
348
349 /**
350 * <p>Gets an appropriate rule for the padding required.</p>
351 *
352 * @param field the field to get a rule for
353 * @param padding the padding required
354 * @return a new rule with the correct padding
355 */
356 protected NumberRule selectNumberRule(final int field, final int padding) {
357 switch (padding) {
358 case 1:
359 return new UnpaddedNumberField(field);
360 case 2:
361 return new TwoDigitNumberField(field);
362 default:
363 return new PaddedNumberField(field, padding);
364 }
365 }
366
367 // Format methods
368 //-----------------------------------------------------------------------
369 /**
370 * <p>Formats a {@code Date}, {@code Calendar} or
371 * {@code Long} (milliseconds) object.</p>
372 *
373 * @param obj the object to format
374 * @param toAppendTo the buffer to append to
375 * @param pos the position - ignored
376 * @return the buffer passed in
377 */
378 @Override
379 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
380 if (obj instanceof Date) {
381 return format((Date) obj, toAppendTo);
382 } else if (obj instanceof Calendar) {
383 return format((Calendar) obj, toAppendTo);
384 } else if (obj instanceof Long) {
385 return format(((Long) obj).longValue(), toAppendTo);
386 } else {
387 throw new IllegalArgumentException("Unknown class: " +
388 (obj == null ? "<null>" : obj.getClass().getName()));
389 }
390 }
391
392 /* (non-Javadoc)
393 * @see org.apache.commons.lang3.time.DatePrinter#format(long)
394 */
395 @Override
396 public String format(final long millis) {
397 final Calendar c = newCalendar(); // hard code GregorianCalendar
398 c.setTimeInMillis(millis);
399 return applyRulesToString(c);
400 }
401
402 /**
403 * Creates a String representation of the given Calendar by applying the rules of this printer to it.
404 * @param c the Calender to apply the rules to.
405 * @return a String representation of the given Calendar.
406 */
407 private String applyRulesToString(final Calendar c) {
408 return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();
409 }
410
411 /**
412 * Creation method for ne calender instances.
413 * @return a new Calendar instance.
414 */
415 private GregorianCalendar newCalendar() {
416 // hard code GregorianCalendar
417 return new GregorianCalendar(mTimeZone, mLocale);
418 }
419
420 /* (non-Javadoc)
421 * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date)
422 */
423 @Override
424 public String format(final Date date) {
425 final Calendar c = newCalendar(); // hard code GregorianCalendar
426 c.setTime(date);
427 return applyRulesToString(c);
428 }
429
430 /* (non-Javadoc)
431 * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar)
432 */
433 @Override
434 public String format(final Calendar calendar) {
435 return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString();
436 }
437
438 /* (non-Javadoc)
439 * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer)
440 */
441 @Override
442 public StringBuffer format(final long millis, final StringBuffer buf) {
443 return format(new Date(millis), buf);
444 }
445
446 /* (non-Javadoc)
447 * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer)
448 */
449 @Override
450 public StringBuffer format(final Date date, final StringBuffer buf) {
451 final Calendar c = newCalendar(); // hard code GregorianCalendar
452 c.setTime(date);
453 return applyRules(c, buf);
454 }
455
456 /* (non-Javadoc)
457 * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer)
458 */
459 @Override
460 public StringBuffer format(final Calendar calendar, final StringBuffer buf) {
461 return applyRules(calendar, buf);
462 }
463
464 /**
465 * <p>Performs the formatting by applying the rules to the
466 * specified calendar.</p>
467 *
468 * @param calendar the calendar to format
469 * @param buf the buffer to format into
470 * @return the specified string buffer
471 */
472 protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) {
473 for (final Rule rule : mRules) {
474 rule.appendTo(buf, calendar);
475 }
476 return buf;
477 }
478
479 // Accessors
480 //-----------------------------------------------------------------------
481 /* (non-Javadoc)
482 * @see org.apache.commons.lang3.time.DatePrinter#getPattern()
483 */
484 @Override
485 public String getPattern() {
486 return mPattern;
487 }
488
489 /* (non-Javadoc)
490 * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone()
491 */
492 @Override
493 public TimeZone getTimeZone() {
494 return mTimeZone;
495 }
496
497 /* (non-Javadoc)
498 * @see org.apache.commons.lang3.time.DatePrinter#getLocale()
499 */
500 @Override
501 public Locale getLocale() {
502 return mLocale;
503 }
504
505 /**
506 * <p>Gets an estimate for the maximum string length that the
507 * formatter will produce.</p>
508 *
509 * <p>The actual formatted length will almost always be less than or
510 * equal to this amount.</p>
511 *
512 * @return the maximum formatted length
513 */
514 public int getMaxLengthEstimate() {
515 return mMaxLengthEstimate;
516 }
517
518 // Basics
519 //-----------------------------------------------------------------------
520 /**
521 * <p>Compares two objects for equality.</p>
522 *
523 * @param obj the object to compare to
524 * @return {@code true} if equal
525 */
526 @Override
527 public boolean equals(final Object obj) {
528 if (obj instanceof FastDatePrinter == false) {
529 return false;
530 }
531 final FastDatePrinter other = (FastDatePrinter) obj;
532 return mPattern.equals(other.mPattern)
533 && mTimeZone.equals(other.mTimeZone)
534 && mLocale.equals(other.mLocale);
535 }
536
537 /**
538 * <p>Returns a hashcode compatible with equals.</p>
539 *
540 * @return a hashcode compatible with equals
541 */
542 @Override
543 public int hashCode() {
544 return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode());
545 }
546
547 /**
548 * <p>Gets a debugging string version of this formatter.</p>
549 *
550 * @return a debugging string
551 */
552 @Override
553 public String toString() {
554 return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]";
555 }
556
557 // Serializing
558 //-----------------------------------------------------------------------
559 /**
560 * Create the object after serialization. This implementation reinitializes the
561 * transient properties.
562 *
563 * @param in ObjectInputStream from which the object is being deserialized.
564 * @throws IOException if there is an IO issue.
565 * @throws ClassNotFoundException if a class cannot be found.
566 */
567 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
568 in.defaultReadObject();
569 init();
570 }
571
572 // Rules
573 //-----------------------------------------------------------------------
574 /**
575 * <p>Inner class defining a rule.</p>
576 */
577 private interface Rule {
578 /**
579 * Returns the estimated lentgh of the result.
580 *
581 * @return the estimated length
582 */
583 int estimateLength();
584
585 /**
586 * Appends the value of the specified calendar to the output buffer based on the rule implementation.
587 *
588 * @param buffer the output buffer
589 * @param calendar calendar to be appended
590 */
591 void appendTo(StringBuffer buffer, Calendar calendar);
592 }
593
594 /**
595 * <p>Inner class defining a numeric rule.</p>
596 */
597 private interface NumberRule extends Rule {
598 /**
599 * Appends the specified value to the output buffer based on the rule implementation.
600 *
601 * @param buffer the output buffer
602 * @param value the value to be appended
603 */
604 void appendTo(StringBuffer buffer, int value);
605 }
606
607 /**
608 * <p>Inner class to output a constant single character.</p>
609 */
610 private static class CharacterLiteral implements Rule {
611 private final char mValue;
612
613 /**
614 * Constructs a new instance of {@code CharacterLiteral}
615 * to hold the specified value.
616 *
617 * @param value the character literal
618 */
619 CharacterLiteral(final char value) {
620 mValue = value;
621 }
622
623 /**
624 * {@inheritDoc}
625 */
626 @Override
627 public int estimateLength() {
628 return 1;
629 }
630
631 /**
632 * {@inheritDoc}
633 */
634 @Override
635 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
636 buffer.append(mValue);
637 }
638 }
639
640 /**
641 * <p>Inner class to output a constant string.</p>
642 */
643 private static class StringLiteral implements Rule {
644 private final String mValue;
645
646 /**
647 * Constructs a new instance of {@code StringLiteral}
648 * to hold the specified value.
649 *
650 * @param value the string literal
651 */
652 StringLiteral(final String value) {
653 mValue = value;
654 }
655
656 /**
657 * {@inheritDoc}
658 */
659 @Override
660 public int estimateLength() {
661 return mValue.length();
662 }
663
664 /**
665 * {@inheritDoc}
666 */
667 @Override
668 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
669 buffer.append(mValue);
670 }
671 }
672
673 /**
674 * <p>Inner class to output one of a set of values.</p>
675 */
676 private static class TextField implements Rule {
677 private final int mField;
678 private final String[] mValues;
679
680 /**
681 * Constructs an instance of {@code TextField}
682 * with the specified field and values.
683 *
684 * @param field the field
685 * @param values the field values
686 */
687 TextField(final int field, final String[] values) {
688 mField = field;
689 mValues = values;
690 }
691
692 /**
693 * {@inheritDoc}
694 */
695 @Override
696 public int estimateLength() {
697 int max = 0;
698 for (int i=mValues.length; --i >= 0; ) {
699 final int len = mValues[i].length();
700 if (len > max) {
701 max = len;
702 }
703 }
704 return max;
705 }
706
707 /**
708 * {@inheritDoc}
709 */
710 @Override
711 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
712 buffer.append(mValues[calendar.get(mField)]);
713 }
714 }
715
716 /**
717 * <p>Inner class to output an unpadded number.</p>
718 */
719 private static class UnpaddedNumberField implements NumberRule {
720 private final int mField;
721
722 /**
723 * Constructs an instance of {@code UnpadedNumberField} with the specified field.
724 *
725 * @param field the field
726 */
727 UnpaddedNumberField(final int field) {
728 mField = field;
729 }
730
731 /**
732 * {@inheritDoc}
733 */
734 @Override
735 public int estimateLength() {
736 return 4;
737 }
738
739 /**
740 * {@inheritDoc}
741 */
742 @Override
743 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
744 appendTo(buffer, calendar.get(mField));
745 }
746
747 /**
748 * {@inheritDoc}
749 */
750 @Override
751 public final void appendTo(final StringBuffer buffer, final int value) {
752 if (value < 10) {
753 buffer.append((char)(value + '0'));
754 } else if (value < 100) {
755 buffer.append((char)(value / 10 + '0'));
756 buffer.append((char)(value % 10 + '0'));
757 } else {
758 buffer.append(Integer.toString(value));
759 }
760 }
761 }
762
763 /**
764 * <p>Inner class to output an unpadded month.</p>
765 */
766 private static class UnpaddedMonthField implements NumberRule {
767 static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField();
768
769 /**
770 * Constructs an instance of {@code UnpaddedMonthField}.
771 *
772 */
773 UnpaddedMonthField() {
774 super();
775 }
776
777 /**
778 * {@inheritDoc}
779 */
780 @Override
781 public int estimateLength() {
782 return 2;
783 }
784
785 /**
786 * {@inheritDoc}
787 */
788 @Override
789 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
790 appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
791 }
792
793 /**
794 * {@inheritDoc}
795 */
796 @Override
797 public final void appendTo(final StringBuffer buffer, final int value) {
798 if (value < 10) {
799 buffer.append((char)(value + '0'));
800 } else {
801 buffer.append((char)(value / 10 + '0'));
802 buffer.append((char)(value % 10 + '0'));
803 }
804 }
805 }
806
807 /**
808 * <p>Inner class to output a padded number.</p>
809 */
810 private static class PaddedNumberField implements NumberRule {
811 private final int mField;
812 private final int mSize;
813
814 /**
815 * Constructs an instance of {@code PaddedNumberField}.
816 *
817 * @param field the field
818 * @param size size of the output field
819 */
820 PaddedNumberField(final int field, final int size) {
821 if (size < 3) {
822 // Should use UnpaddedNumberField or TwoDigitNumberField.
823 throw new IllegalArgumentException();
824 }
825 mField = field;
826 mSize = size;
827 }
828
829 /**
830 * {@inheritDoc}
831 */
832 @Override
833 public int estimateLength() {
834 return 4;
835 }
836
837 /**
838 * {@inheritDoc}
839 */
840 @Override
841 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
842 appendTo(buffer, calendar.get(mField));
843 }
844
845 /**
846 * {@inheritDoc}
847 */
848 @Override
849 public final void appendTo(final StringBuffer buffer, final int value) {
850 if (value < 100) {
851 for (int i = mSize; --i >= 2; ) {
852 buffer.append('0');
853 }
854 buffer.append((char)(value / 10 + '0'));
855 buffer.append((char)(value % 10 + '0'));
856 } else {
857 int digits;
858 if (value < 1000) {
859 digits = 3;
860 } else {
861 Validate.isTrue(value > -1, "Negative values should not be possible", value);
862 digits = Integer.toString(value).length();
863 }
864 for (int i = mSize; --i >= digits; ) {
865 buffer.append('0');
866 }
867 buffer.append(Integer.toString(value));
868 }
869 }
870 }
871
872 /**
873 * <p>Inner class to output a two digit number.</p>
874 */
875 private static class TwoDigitNumberField implements NumberRule {
876 private final int mField;
877
878 /**
879 * Constructs an instance of {@code TwoDigitNumberField} with the specified field.
880 *
881 * @param field the field
882 */
883 TwoDigitNumberField(final int field) {
884 mField = field;
885 }
886
887 /**
888 * {@inheritDoc}
889 */
890 @Override
891 public int estimateLength() {
892 return 2;
893 }
894
895 /**
896 * {@inheritDoc}
897 */
898 @Override
899 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
900 appendTo(buffer, calendar.get(mField));
901 }
902
903 /**
904 * {@inheritDoc}
905 */
906 @Override
907 public final void appendTo(final StringBuffer buffer, final int value) {
908 if (value < 100) {
909 buffer.append((char)(value / 10 + '0'));
910 buffer.append((char)(value % 10 + '0'));
911 } else {
912 buffer.append(Integer.toString(value));
913 }
914 }
915 }
916
917 /**
918 * <p>Inner class to output a two digit year.</p>
919 */
920 private static class TwoDigitYearField implements NumberRule {
921 static final TwoDigitYearField INSTANCE = new TwoDigitYearField();
922
923 /**
924 * Constructs an instance of {@code TwoDigitYearField}.
925 */
926 TwoDigitYearField() {
927 super();
928 }
929
930 /**
931 * {@inheritDoc}
932 */
933 @Override
934 public int estimateLength() {
935 return 2;
936 }
937
938 /**
939 * {@inheritDoc}
940 */
941 @Override
942 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
943 appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
944 }
945
946 /**
947 * {@inheritDoc}
948 */
949 @Override
950 public final void appendTo(final StringBuffer buffer, final int value) {
951 buffer.append((char)(value / 10 + '0'));
952 buffer.append((char)(value % 10 + '0'));
953 }
954 }
955
956 /**
957 * <p>Inner class to output a two digit month.</p>
958 */
959 private static class TwoDigitMonthField implements NumberRule {
960 static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
961
962 /**
963 * Constructs an instance of {@code TwoDigitMonthField}.
964 */
965 TwoDigitMonthField() {
966 super();
967 }
968
969 /**
970 * {@inheritDoc}
971 */
972 @Override
973 public int estimateLength() {
974 return 2;
975 }
976
977 /**
978 * {@inheritDoc}
979 */
980 @Override
981 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
982 appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
983 }
984
985 /**
986 * {@inheritDoc}
987 */
988 @Override
989 public final void appendTo(final StringBuffer buffer, final int value) {
990 buffer.append((char)(value / 10 + '0'));
991 buffer.append((char)(value % 10 + '0'));
992 }
993 }
994
995 /**
996 * <p>Inner class to output the twelve hour field.</p>
997 */
998 private static class TwelveHourField implements NumberRule {
999 private final NumberRule mRule;
1000
1001 /**
1002 * Constructs an instance of {@code TwelveHourField} with the specified
1003 * {@code NumberRule}.
1004 *
1005 * @param rule the rule
1006 */
1007 TwelveHourField(final NumberRule rule) {
1008 mRule = rule;
1009 }
1010
1011 /**
1012 * {@inheritDoc}
1013 */
1014 @Override
1015 public int estimateLength() {
1016 return mRule.estimateLength();
1017 }
1018
1019 /**
1020 * {@inheritDoc}
1021 */
1022 @Override
1023 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1024 int value = calendar.get(Calendar.HOUR);
1025 if (value == 0) {
1026 value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
1027 }
1028 mRule.appendTo(buffer, value);
1029 }
1030
1031 /**
1032 * {@inheritDoc}
1033 */
1034 @Override
1035 public void appendTo(final StringBuffer buffer, final int value) {
1036 mRule.appendTo(buffer, value);
1037 }
1038 }
1039
1040 /**
1041 * <p>Inner class to output the twenty four hour field.</p>
1042 */
1043 private static class TwentyFourHourField implements NumberRule {
1044 private final NumberRule mRule;
1045
1046 /**
1047 * Constructs an instance of {@code TwentyFourHourField} with the specified
1048 * {@code NumberRule}.
1049 *
1050 * @param rule the rule
1051 */
1052 TwentyFourHourField(final NumberRule rule) {
1053 mRule = rule;
1054 }
1055
1056 /**
1057 * {@inheritDoc}
1058 */
1059 @Override
1060 public int estimateLength() {
1061 return mRule.estimateLength();
1062 }
1063
1064 /**
1065 * {@inheritDoc}
1066 */
1067 @Override
1068 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1069 int value = calendar.get(Calendar.HOUR_OF_DAY);
1070 if (value == 0) {
1071 value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
1072 }
1073 mRule.appendTo(buffer, value);
1074 }
1075
1076 /**
1077 * {@inheritDoc}
1078 */
1079 @Override
1080 public void appendTo(final StringBuffer buffer, final int value) {
1081 mRule.appendTo(buffer, value);
1082 }
1083 }
1084
1085 //-----------------------------------------------------------------------
1086
1087 private static ConcurrentMap<TimeZoneDisplayKey, String> cTimeZoneDisplayCache =
1088 new ConcurrentHashMap<TimeZoneDisplayKey, String>(7);
1089 /**
1090 * <p>Gets the time zone display name, using a cache for performance.</p>
1091 *
1092 * @param tz the zone to query
1093 * @param daylight true if daylight savings
1094 * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT}
1095 * @param locale the locale to use
1096 * @return the textual name of the time zone
1097 */
1098 static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) {
1099 final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale);
1100 String value = cTimeZoneDisplayCache.get(key);
1101 if (value == null) {
1102 // This is a very slow call, so cache the results.
1103 value = tz.getDisplayName(daylight, style, locale);
1104 final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value);
1105 if (prior != null) {
1106 value= prior;
1107 }
1108 }
1109 return value;
1110 }
1111
1112 /**
1113 * <p>Inner class to output a time zone name.</p>
1114 */
1115 private static class TimeZoneNameRule implements Rule {
1116 private final Locale mLocale;
1117 private final int mStyle;
1118 private final String mStandard;
1119 private final String mDaylight;
1120
1121 /**
1122 * Constructs an instance of {@code TimeZoneNameRule} with the specified properties.
1123 *
1124 * @param timeZone the time zone
1125 * @param locale the locale
1126 * @param style the style
1127 */
1128 TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) {
1129 mLocale = locale;
1130 mStyle = style;
1131
1132 mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
1133 mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
1134 }
1135
1136 /**
1137 * {@inheritDoc}
1138 */
1139 @Override
1140 public int estimateLength() {
1141 // We have no access to the Calendar object that will be passed to
1142 // appendTo so base estimate on the TimeZone passed to the
1143 // constructor
1144 return Math.max(mStandard.length(), mDaylight.length());
1145 }
1146
1147 /**
1148 * {@inheritDoc}
1149 */
1150 @Override
1151 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1152 final TimeZone zone = calendar.getTimeZone();
1153 if (zone.useDaylightTime()
1154 && calendar.get(Calendar.DST_OFFSET) != 0) {
1155 buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale));
1156 } else {
1157 buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale));
1158 }
1159 }
1160 }
1161
1162 /**
1163 * <p>Inner class to output a time zone as a number {@code +/-HHMM}
1164 * or {@code +/-HH:MM}.</p>
1165 */
1166 private static class TimeZoneNumberRule implements Rule {
1167 static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true);
1168 static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false);
1169
1170 final boolean mColon;
1171
1172 /**
1173 * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties.
1174 *
1175 * @param colon add colon between HH and MM in the output if {@code true}
1176 */
1177 TimeZoneNumberRule(final boolean colon) {
1178 mColon = colon;
1179 }
1180
1181 /**
1182 * {@inheritDoc}
1183 */
1184 @Override
1185 public int estimateLength() {
1186 return 5;
1187 }
1188
1189 /**
1190 * {@inheritDoc}
1191 */
1192 @Override
1193 public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1194 int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
1195
1196 if (offset < 0) {
1197 buffer.append('-');
1198 offset = -offset;
1199 } else {
1200 buffer.append('+');
1201 }
1202
1203 final int hours = offset / (60 * 60 * 1000);
1204 buffer.append((char)(hours / 10 + '0'));
1205 buffer.append((char)(hours % 10 + '0'));
1206
1207 if (mColon) {
1208 buffer.append(':');
1209 }
1210
1211 final int minutes = offset / (60 * 1000) - 60 * hours;
1212 buffer.append((char)(minutes / 10 + '0'));
1213 buffer.append((char)(minutes % 10 + '0'));
1214 }
1215 }
1216
1217 // ----------------------------------------------------------------------
1218 /**
1219 * <p>Inner class that acts as a compound key for time zone names.</p>
1220 */
1221 private static class TimeZoneDisplayKey {
1222 private final TimeZone mTimeZone;
1223 private final int mStyle;
1224 private final Locale mLocale;
1225
1226 /**
1227 * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties.
1228 *
1229 * @param timeZone the time zone
1230 * @param daylight adjust the style for daylight saving time if {@code true}
1231 * @param style the timezone style
1232 * @param locale the timezone locale
1233 */
1234 TimeZoneDisplayKey(final TimeZone timeZone,
1235 final boolean daylight, int style, final Locale locale) {
1236 mTimeZone = timeZone;
1237 if (daylight) {
1238 style |= 0x80000000;
1239 }
1240 mStyle = style;
1241 mLocale = locale;
1242 }
1243
1244 /**
1245 * {@inheritDoc}
1246 */
1247 @Override
1248 public int hashCode() {
1249 return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode();
1250 }
1251
1252 /**
1253 * {@inheritDoc}
1254 */
1255 @Override
1256 public boolean equals(final Object obj) {
1257 if (this == obj) {
1258 return true;
1259 }
1260 if (obj instanceof TimeZoneDisplayKey) {
1261 final TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
1262 return
1263 mTimeZone.equals(other.mTimeZone) &&
1264 mStyle == other.mStyle &&
1265 mLocale.equals(other.mLocale);
1266 }
1267 return false;
1268 }
1269 }
1270 }
4040 private final ConcurrentMap<MultipartKey, F> cInstanceCache
4141 = new ConcurrentHashMap<MultipartKey, F>(7);
4242
43 private final ConcurrentMap<MultipartKey, String> cDateTimeInstanceCache
43 private static final ConcurrentMap<MultipartKey, String> cDateTimeInstanceCache
4444 = new ConcurrentHashMap<MultipartKey, String>(7);
4545
4646 /**
5858 * and locale.</p>
5959 *
6060 * @param pattern {@link java.text.SimpleDateFormat} compatible
61 * pattern
62 * @param timeZone the non-null time zone
63 * @param locale the non-null locale
61 * pattern, non-null
62 * @param timeZone the time zone, null means use the default TimeZone
63 * @param locale the locale, null means use the default Locale
6464 * @return a pattern based date/time formatter
6565 * @throws IllegalArgumentException if pattern is invalid
6666 * or <code>null</code>
6767 */
68 public F getInstance(String pattern, TimeZone timeZone, Locale locale) {
68 public F getInstance(final String pattern, TimeZone timeZone, Locale locale) {
6969 if (pattern == null) {
7070 throw new NullPointerException("pattern must not be null");
7171 }
7575 if (locale == null) {
7676 locale = Locale.getDefault();
7777 }
78 MultipartKey key = new MultipartKey(pattern, timeZone, locale);
78 final MultipartKey key = new MultipartKey(pattern, timeZone, locale);
7979 F format = cInstanceCache.get(key);
8080 if (format == null) {
8181 format = createInstance(pattern, timeZone, locale);
82 F previousValue= cInstanceCache.putIfAbsent(key, format);
82 final F previousValue= cInstanceCache.putIfAbsent(key, format);
8383 if (previousValue != null) {
8484 // another thread snuck in and did the same work
8585 // we should return the instance that is in ConcurrentMap
106106 * <p>Gets a date/time formatter instance using the specified style,
107107 * time zone and locale.</p>
108108 *
109 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format
110 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format
111 * @param timeZone optional time zone, overrides time zone of
112 * formatted date, null means use default Locale
113 * @param locale optional locale, overrides system locale
114 * @return a localized standard date/time formatter
115 * @throws IllegalArgumentException if the Locale has no date/time
116 * pattern defined
117 */
118 // This must remain private, see LANG-884
119 private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, Locale locale) {
120 if (locale == null) {
121 locale = Locale.getDefault();
122 }
123 final String pattern = getPatternForStyle(dateStyle, timeStyle, locale);
124 return getInstance(pattern, timeZone, locale);
125 }
126
127 /**
128 * <p>Gets a date/time formatter instance using the specified style,
129 * time zone and locale.</p>
130 *
109131 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT
110132 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT
111133 * @param timeZone optional time zone, overrides time zone of
112 * formatted date
113 * @param locale optional locale, overrides system locale
114 * @return a localized standard date/time formatter
115 * @throws IllegalArgumentException if the Locale has no date/time
116 * pattern defined
117 */
118 public F getDateTimeInstance(Integer dateStyle, Integer timeStyle, TimeZone timeZone, Locale locale) {
119 if (locale == null) {
120 locale = Locale.getDefault();
121 }
122 MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale);
134 * formatted date, null means use default Locale
135 * @param locale optional locale, overrides system locale
136 * @return a localized standard date/time formatter
137 * @throws IllegalArgumentException if the Locale has no date/time
138 * pattern defined
139 */
140 // package protected, for access from FastDateFormat; do not make public or protected
141 F getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone, Locale locale) {
142 return getDateTimeInstance(Integer.valueOf(dateStyle), Integer.valueOf(timeStyle), timeZone, locale);
143 }
144
145 /**
146 * <p>Gets a date formatter instance using the specified style,
147 * time zone and locale.</p>
148 *
149 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT
150 * @param timeZone optional time zone, overrides time zone of
151 * formatted date, null means use default Locale
152 * @param locale optional locale, overrides system locale
153 * @return a localized standard date/time formatter
154 * @throws IllegalArgumentException if the Locale has no date/time
155 * pattern defined
156 */
157 // package protected, for access from FastDateFormat; do not make public or protected
158 F getDateInstance(final int dateStyle, final TimeZone timeZone, Locale locale) {
159 return getDateTimeInstance(Integer.valueOf(dateStyle), null, timeZone, locale);
160 }
161
162 /**
163 * <p>Gets a time formatter instance using the specified style,
164 * time zone and locale.</p>
165 *
166 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT
167 * @param timeZone optional time zone, overrides time zone of
168 * formatted date, null means use default Locale
169 * @param locale optional locale, overrides system locale
170 * @return a localized standard date/time formatter
171 * @throws IllegalArgumentException if the Locale has no date/time
172 * pattern defined
173 */
174 // package protected, for access from FastDateFormat; do not make public or protected
175 F getTimeInstance(final int timeStyle, final TimeZone timeZone, Locale locale) {
176 return getDateTimeInstance(null, Integer.valueOf(timeStyle), timeZone, locale);
177 }
178
179 /**
180 * <p>Gets a date/time format for the specified styles and locale.</p>
181 *
182 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format
183 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format
184 * @param locale The non-null locale of the desired format
185 * @return a localized standard date/time format
186 * @throws IllegalArgumentException if the Locale has no date/time pattern defined
187 */
188 // package protected, for access from test code; do not make public or protected
189 static String getPatternForStyle(final Integer dateStyle, final Integer timeStyle, final Locale locale) {
190 final MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale);
123191
124192 String pattern = cDateTimeInstanceCache.get(key);
125193 if (pattern == null) {
126194 try {
127195 DateFormat formatter;
128196 if (dateStyle == null) {
129 formatter = DateFormat.getTimeInstance(timeStyle, locale);
197 formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale);
130198 }
131199 else if (timeStyle == null) {
132 formatter = DateFormat.getDateInstance(dateStyle, locale);
200 formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale);
133201 }
134202 else {
135 formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
203 formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale);
136204 }
137205 pattern = ((SimpleDateFormat)formatter).toPattern();
138 String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern);
206 final String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern);
139207 if (previous != null) {
140208 // even though it doesn't matter if another thread put the pattern
141209 // it's still good practice to return the String instance that is
142210 // actually in the ConcurrentMap
143211 pattern= previous;
144212 }
145 } catch (ClassCastException ex) {
213 } catch (final ClassCastException ex) {
146214 throw new IllegalArgumentException("No date time pattern for locale: " + locale);
147215 }
148216 }
149
150 return getInstance(pattern, timeZone, locale);
217 return pattern;
151218 }
152219
153220 // ----------------------------------------------------------------------
162229 * Constructs an instance of <code>MultipartKey</code> to hold the specified objects.
163230 * @param keys the set of objects that make up the key. Each key may be null.
164231 */
165 public MultipartKey(Object... keys) {
232 public MultipartKey(final Object... keys) {
166233 this.keys = keys;
167234 }
168235
170237 * {@inheritDoc}
171238 */
172239 @Override
173 public boolean equals(Object obj) {
174 if (this == obj) {
175 return true;
176 }
177 if ( obj instanceof MultipartKey == false ) {
178 return false;
179 }
240 public boolean equals(final Object obj) {
241 // Eliminate the usual boilerplate because
242 // this inner static class is only used in a generic ConcurrentHashMap
243 // which will not compare against other Object types
180244 return Arrays.equals(keys, ((MultipartKey)obj).keys);
181245 }
182246
187251 public int hashCode() {
188252 if(hashCode==0) {
189253 int rc= 0;
190 for(Object key : keys) {
254 for(final Object key : keys) {
191255 if(key!=null) {
192256 rc= rc*7 + key.hashCode();
193257 }
5252 * <p>This class is not thread-safe</p>
5353 *
5454 * @since 2.0
55 * @version $Id: StopWatch.java 1199894 2011-11-09 17:53:59Z ggregory $
55 * @version $Id: StopWatch.java 1552682 2013-12-20 14:19:09Z britter $
5656 */
5757 public class StopWatch {
5858
5959 private static final long NANO_2_MILLIS = 1000000L;
60
61 // running states
62 private static final int STATE_UNSTARTED = 0;
63
64 private static final int STATE_RUNNING = 1;
65
66 private static final int STATE_STOPPED = 2;
67
68 private static final int STATE_SUSPENDED = 3;
69
70 // split state
71 private static final int STATE_UNSPLIT = 10;
72
73 private static final int STATE_SPLIT = 11;
74
60
61 /**
62 * Enumeration type which indicates the status of stopwatch.
63 */
64 private enum State {
65
66 UNSTARTED {
67 @Override boolean isStarted() { return false; }
68 @Override boolean isStopped() { return true; }
69 @Override boolean isSuspended() { return false; }
70 },
71 RUNNING {
72 @Override boolean isStarted() { return true; }
73 @Override boolean isStopped() { return false; }
74 @Override boolean isSuspended() { return false; }
75 },
76 STOPPED {
77 @Override boolean isStarted() { return false; }
78 @Override boolean isStopped() { return true; }
79 @Override boolean isSuspended() { return false; }
80 },
81 SUSPENDED {
82 @Override boolean isStarted() { return true; }
83 @Override boolean isStopped() { return false; }
84 @Override boolean isSuspended() { return true; }
85 };
86
87 /**
88 * <p>
89 * The method is used to find out if the StopWatch is started. A suspended
90 * StopWatch is also started watch.
91 * </p>
92
93 * @param stopWatch
94 * @return boolean
95 * If the StopWatch is started.
96 */
97 abstract boolean isStarted();
98
99 /**
100 * <p>
101 * This method is used to find out whether the StopWatch is stopped. The
102 * stopwatch which's not yet started and explicitly stopped stopwatch is
103 * considered as stopped.
104 * </p>
105 *
106 * @param stopWatch
107 * @return boolean
108 * If the StopWatch is stopped.
109 */
110 abstract boolean isStopped();
111
112 /**
113 * <p>
114 * This method is used to find out whether the StopWatch is suspended.
115 * </p>
116 *
117 * @param stopWatch
118 * @return boolean
119 * If the StopWatch is suspended.
120 */
121 abstract boolean isSuspended();
122 }
123
124 /**
125 * Enumeration type which indicates the split status of stopwatch.
126 */
127 private enum SplitState {
128 SPLIT,
129 UNSPLIT
130 }
75131 /**
76132 * The current running state of the StopWatch.
77133 */
78 private int runningState = STATE_UNSTARTED;
134 private State runningState = State.UNSTARTED;
79135
80136 /**
81137 * Whether the stopwatch has a split time recorded.
82138 */
83 private int splitState = STATE_UNSPLIT;
139 private SplitState splitState = SplitState.UNSPLIT;
84140
85141 /**
86142 * The start time.
121177 * if the StopWatch is already running.
122178 */
123179 public void start() {
124 if (this.runningState == STATE_STOPPED) {
180 if (this.runningState == State.STOPPED) {
125181 throw new IllegalStateException("Stopwatch must be reset before being restarted. ");
126182 }
127 if (this.runningState != STATE_UNSTARTED) {
183 if (this.runningState != State.UNSTARTED) {
128184 throw new IllegalStateException("Stopwatch already started. ");
129185 }
130186 this.startTime = System.nanoTime();
131187 this.startTimeMillis = System.currentTimeMillis();
132 this.runningState = STATE_RUNNING;
133 }
188 this.runningState = State.RUNNING;
189 }
190
134191
135192 /**
136193 * <p>
145202 * if the StopWatch is not running.
146203 */
147204 public void stop() {
148 if (this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {
205 if (this.runningState != State.RUNNING && this.runningState != State.SUSPENDED) {
149206 throw new IllegalStateException("Stopwatch is not running. ");
150207 }
151 if (this.runningState == STATE_RUNNING) {
208 if (this.runningState == State.RUNNING) {
152209 this.stopTime = System.nanoTime();
153210 }
154 this.runningState = STATE_STOPPED;
211 this.runningState = State.STOPPED;
155212 }
156213
157214 /**
164221 * </p>
165222 */
166223 public void reset() {
167 this.runningState = STATE_UNSTARTED;
168 this.splitState = STATE_UNSPLIT;
224 this.runningState = State.UNSTARTED;
225 this.splitState = SplitState.UNSPLIT;
169226 }
170227
171228 /**
182239 * if the StopWatch is not running.
183240 */
184241 public void split() {
185 if (this.runningState != STATE_RUNNING) {
242 if (this.runningState != State.RUNNING) {
186243 throw new IllegalStateException("Stopwatch is not running. ");
187244 }
188245 this.stopTime = System.nanoTime();
189 this.splitState = STATE_SPLIT;
246 this.splitState = SplitState.SPLIT;
190247 }
191248
192249 /**
203260 * if the StopWatch has not been split.
204261 */
205262 public void unsplit() {
206 if (this.splitState != STATE_SPLIT) {
263 if (this.splitState != SplitState.SPLIT) {
207264 throw new IllegalStateException("Stopwatch has not been split. ");
208265 }
209 this.splitState = STATE_UNSPLIT;
266 this.splitState = SplitState.UNSPLIT;
210267 }
211268
212269 /**
223280 * if the StopWatch is not currently running.
224281 */
225282 public void suspend() {
226 if (this.runningState != STATE_RUNNING) {
283 if (this.runningState != State.RUNNING) {
227284 throw new IllegalStateException("Stopwatch must be running to suspend. ");
228285 }
229286 this.stopTime = System.nanoTime();
230 this.runningState = STATE_SUSPENDED;
287 this.runningState = State.SUSPENDED;
231288 }
232289
233290 /**
244301 * if the StopWatch has not been suspended.
245302 */
246303 public void resume() {
247 if (this.runningState != STATE_SUSPENDED) {
304 if (this.runningState != State.SUSPENDED) {
248305 throw new IllegalStateException("Stopwatch must be suspended to resume. ");
249306 }
250307 this.startTime += System.nanoTime() - this.stopTime;
251 this.runningState = STATE_RUNNING;
308 this.runningState = State.RUNNING;
252309 }
253310
254311 /**
280337 * @since 3.0
281338 */
282339 public long getNanoTime() {
283 if (this.runningState == STATE_STOPPED || this.runningState == STATE_SUSPENDED) {
340 if (this.runningState == State.STOPPED || this.runningState == State.SUSPENDED) {
284341 return this.stopTime - this.startTime;
285 } else if (this.runningState == STATE_UNSTARTED) {
342 } else if (this.runningState == State.UNSTARTED) {
286343 return 0;
287 } else if (this.runningState == STATE_RUNNING) {
344 } else if (this.runningState == State.RUNNING) {
288345 return System.nanoTime() - this.startTime;
289346 }
290 throw new RuntimeException("Illegal running state has occured. ");
347 throw new RuntimeException("Illegal running state has occurred.");
291348 }
292349
293350 /**
324381 * @since 3.0
325382 */
326383 public long getSplitNanoTime() {
327 if (this.splitState != STATE_SPLIT) {
384 if (this.splitState != SplitState.SPLIT) {
328385 throw new IllegalStateException("Stopwatch must be split to get the split time. ");
329386 }
330387 return this.stopTime - this.startTime;
339396 * @since 2.4
340397 */
341398 public long getStartTime() {
342 if (this.runningState == STATE_UNSTARTED) {
399 if (this.runningState == State.UNSTARTED) {
343400 throw new IllegalStateException("Stopwatch has not been started");
344401 }
345402 // System.nanoTime is for elapsed time
378435 return DurationFormatUtils.formatDurationHMS(getSplitTime());
379436 }
380437
438 /**
439 * <p>
440 * The method is used to find out if the StopWatch is started. A suspended
441 * StopWatch is also started watch.
442 * </p>
443 *
444 * @return boolean
445 * If the StopWatch is started.
446 * @since 3.2
447 */
448 public boolean isStarted() {
449 return runningState.isStarted();
450 }
451
452 /**
453 * <p>
454 * This method is used to find out whether the StopWatch is suspended.
455 * </p>
456 *
457 * @return boolean
458 * If the StopWatch is suspended.
459 * @since 3.2
460 */
461 public boolean isSuspended() {
462 return runningState.isSuspended();
463 }
464
465 /**
466 * <p>
467 * This method is used to find out whether the StopWatch is stopped. The
468 * stopwatch which's not yet started and explicitly stopped stopwatch is
469 * considered as stopped.
470 * </p>
471 *
472 * @return boolean
473 * If the StopWatch is stopped.
474 * @since 3.2
475 */
476 public boolean isStopped() {
477 return runningState.isStopped();
478 }
479
381480 }
2323 * itself effectively becomes mutable. The class is also not {@code final}, so a subclass
2424 * could add undesirable behaviour.</p>
2525 *
26 * <p>#ThreadSafe# if the objects are threadsafe</p>
26 * <p>#ThreadSafe# if both paired objects are thread-safe</p>
2727 *
2828 * @param <L> the left element type
2929 * @param <R> the right element type
3030 *
3131 * @since Lang 3.0
32 * @version $Id: ImmutablePair.java 1127544 2011-05-25 14:35:42Z scolebourne $
32 * @version $Id: ImmutablePair.java 1436768 2013-01-22 07:07:42Z ggregory $
3333 */
3434 public final class ImmutablePair<L, R> extends Pair<L, R> {
3535
5353 * @param right the right element, may be null
5454 * @return a pair formed from the two parameters, not null
5555 */
56 public static <L, R> ImmutablePair<L, R> of(L left, R right) {
56 public static <L, R> ImmutablePair<L, R> of(final L left, final R right) {
5757 return new ImmutablePair<L, R>(left, right);
5858 }
5959
6363 * @param left the left value, may be null
6464 * @param right the right value, may be null
6565 */
66 public ImmutablePair(L left, R right) {
66 public ImmutablePair(final L left, final R right) {
6767 super();
6868 this.left = left;
6969 this.right = right;
9595 * @return never
9696 * @throws UnsupportedOperationException as this operation is not supported
9797 */
98 public R setValue(R value) {
98 @Override
99 public R setValue(final R value) {
99100 throw new UnsupportedOperationException();
100101 }
101102
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.tuple;
17
18 /**
19 * <p>An immutable triple consisting of three {@code Object} elements.</p>
20 *
21 * <p>Although the implementation is immutable, there is no restriction on the objects
22 * that may be stored. If mutable objects are stored in the triple, then the triple
23 * itself effectively becomes mutable. The class is also not {@code final}, so a subclass
24 * could add undesirable behaviour.</p>
25 *
26 * <p>#ThreadSafe# if all three objects are thread-safe</p>
27 *
28 * @param <L> the left element type
29 * @param <M> the middle element type
30 * @param <R> the right element type
31 *
32 * @version $Id: ImmutableTriple.java 1552635 2013-12-20 13:02:03Z britter $
33 * @since 3.2
34 */
35 public final class ImmutableTriple<L, M, R> extends Triple<L, M, R> {
36
37 /** Serialization version */
38 private static final long serialVersionUID = 1L;
39
40 /** Left object */
41 public final L left;
42 /** Middle object */
43 public final M middle;
44 /** Right object */
45 public final R right;
46
47 /**
48 * <p>Obtains an immutable triple of from three objects inferring the generic types.</p>
49 *
50 * <p>This factory allows the triple to be created using inference to
51 * obtain the generic types.</p>
52 *
53 * @param <L> the left element type
54 * @param <M> the middle element type
55 * @param <R> the right element type
56 * @param left the left element, may be null
57 * @param middle the middle element, may be null
58 * @param right the right element, may be null
59 * @return a triple formed from the three parameters, not null
60 */
61 public static <L, M, R> ImmutableTriple<L, M, R> of(final L left, final M middle, final R right) {
62 return new ImmutableTriple<L, M, R>(left, middle, right);
63 }
64
65 /**
66 * Create a new triple instance.
67 *
68 * @param left the left value, may be null
69 * @param middle the middle value, may be null
70 * @param right the right value, may be null
71 */
72 public ImmutableTriple(final L left, final M middle, final R right) {
73 super();
74 this.left = left;
75 this.middle = middle;
76 this.right = right;
77 }
78
79 //-----------------------------------------------------------------------
80 /**
81 * {@inheritDoc}
82 */
83 @Override
84 public L getLeft() {
85 return left;
86 }
87
88 /**
89 * {@inheritDoc}
90 */
91 @Override
92 public M getMiddle() {
93 return middle;
94 }
95
96 /**
97 * {@inheritDoc}
98 */
99 @Override
100 public R getRight() {
101 return right;
102 }
103 }
104
2424 * @param <R> the right element type
2525 *
2626 * @since Lang 3.0
27 * @version $Id: MutablePair.java 1127544 2011-05-25 14:35:42Z scolebourne $
27 * @version $Id: MutablePair.java 1436770 2013-01-22 07:09:45Z ggregory $
2828 */
2929 public class MutablePair<L, R> extends Pair<L, R> {
3030
4848 * @param right the right element, may be null
4949 * @return a pair formed from the two parameters, not null
5050 */
51 public static <L, R> MutablePair<L, R> of(L left, R right) {
51 public static <L, R> MutablePair<L, R> of(final L left, final R right) {
5252 return new MutablePair<L, R>(left, right);
5353 }
5454
6565 * @param left the left value, may be null
6666 * @param right the right value, may be null
6767 */
68 public MutablePair(L left, R right) {
68 public MutablePair(final L left, final R right) {
6969 super();
7070 this.left = left;
7171 this.right = right;
8585 *
8686 * @param left the new value of the left element, may be null
8787 */
88 public void setLeft(L left) {
88 public void setLeft(final L left) {
8989 this.left = left;
9090 }
9191
102102 *
103103 * @param right the new value of the right element, may be null
104104 */
105 public void setRight(R right) {
105 public void setRight(final R right) {
106106 this.right = right;
107107 }
108108
113113 * @param value the right value to set, not null
114114 * @return the old value for the right element
115115 */
116 public R setValue(R value) {
117 R result = getRight();
116 @Override
117 public R setValue(final R value) {
118 final R result = getRight();
118119 setRight(value);
119120 return result;
120121 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.tuple;
17
18 /**
19 * <p>A mutable triple consisting of three {@code Object} elements.</p>
20 *
21 * <p>Not #ThreadSafe#</p>
22 *
23 * @param <L> the left element type
24 * @param <M> the middle element type
25 * @param <R> the right element type
26 *
27 * @version $Id: MutableTriple.java 1552635 2013-12-20 13:02:03Z britter $
28 * @since 3.2
29 */
30 public class MutableTriple<L, M, R> extends Triple<L, M, R> {
31
32 /** Serialization version */
33 private static final long serialVersionUID = 1L;
34
35 /** Left object */
36 public L left;
37 /** Middle object */
38 public M middle;
39 /** Right object */
40 public R right;
41
42 /**
43 * <p>Obtains an mutable triple of three objects inferring the generic types.</p>
44 *
45 * <p>This factory allows the triple to be created using inference to
46 * obtain the generic types.</p>
47 *
48 * @param <L> the left element type
49 * @param <M> the middle element type
50 * @param <R> the right element type
51 * @param left the left element, may be null
52 * @param middle the middle element, may be null
53 * @param right the right element, may be null
54 * @return a triple formed from the three parameters, not null
55 */
56 public static <L, M, R> MutableTriple<L, M, R> of(final L left, final M middle, final R right) {
57 return new MutableTriple<L, M, R>(left, middle, right);
58 }
59
60 /**
61 * Create a new triple instance of three nulls.
62 */
63 public MutableTriple() {
64 super();
65 }
66
67 /**
68 * Create a new triple instance.
69 *
70 * @param left the left value, may be null
71 * @param middle the middle value, may be null
72 * @param right the right value, may be null
73 */
74 public MutableTriple(final L left, final M middle, final R right) {
75 super();
76 this.left = left;
77 this.middle = middle;
78 this.right = right;
79 }
80
81 //-----------------------------------------------------------------------
82 /**
83 * {@inheritDoc}
84 */
85 @Override
86 public L getLeft() {
87 return left;
88 }
89
90 /**
91 * Sets the left element of the triple.
92 *
93 * @param left the new value of the left element, may be null
94 */
95 public void setLeft(final L left) {
96 this.left = left;
97 }
98
99 /**
100 * {@inheritDoc}
101 */
102 @Override
103 public M getMiddle() {
104 return middle;
105 }
106
107 /**
108 * Sets the middle element of the triple.
109 *
110 * @param middle the new value of the middle element, may be null
111 */
112 public void setMiddle(final M middle) {
113 this.middle = middle;
114 }
115
116 /**
117 * {@inheritDoc}
118 */
119 @Override
120 public R getRight() {
121 return right;
122 }
123
124 /**
125 * Sets the right element of the triple.
126 *
127 * @param right the new value of the right element, may be null
128 */
129 public void setRight(final R right) {
130 this.right = right;
131 }
132 }
133
3636 * @param <R> the right element type
3737 *
3838 * @since Lang 3.0
39 * @version $Id: Pair.java 1142401 2011-07-03 08:30:12Z bayard $
39 * @version $Id: Pair.java 1436770 2013-01-22 07:09:45Z ggregory $
4040 */
4141 public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
4242
5555 * @param right the right element, may be null
5656 * @return a pair formed from the two parameters, not null
5757 */
58 public static <L, R> Pair<L, R> of(L left, R right) {
58 public static <L, R> Pair<L, R> of(final L left, final R right) {
5959 return new ImmutablePair<L, R>(left, right);
6060 }
6161
8686 *
8787 * @return the left element as the key, may be null
8888 */
89 @Override
8990 public final L getKey() {
9091 return getLeft();
9192 }
9899 *
99100 * @return the right element as the value, may be null
100101 */
102 @Override
101103 public R getValue() {
102104 return getRight();
103105 }
110112 * @param other the other pair, not null
111113 * @return negative if this is less, zero if equal, positive if greater
112114 */
113 public int compareTo(Pair<L, R> other) {
115 @Override
116 public int compareTo(final Pair<L, R> other) {
114117 return new CompareToBuilder().append(getLeft(), other.getLeft())
115118 .append(getRight(), other.getRight()).toComparison();
116119 }
122125 * @return true if the elements of the pair are equal
123126 */
124127 @Override
125 public boolean equals(Object obj) {
128 public boolean equals(final Object obj) {
126129 if (obj == this) {
127130 return true;
128131 }
129132 if (obj instanceof Map.Entry<?, ?>) {
130 Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
133 final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
131134 return ObjectUtils.equals(getKey(), other.getKey())
132135 && ObjectUtils.equals(getValue(), other.getValue());
133136 }
168171 * @param format the format string, optionally containing {@code %1$s} and {@code %2$s}, not null
169172 * @return the formatted string, not null
170173 */
171 public String toString(String format) {
174 public String toString(final String format) {
172175 return String.format(format, getLeft(), getRight());
173176 }
174177
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.tuple;
17
18 import java.io.Serializable;
19
20 import org.apache.commons.lang3.ObjectUtils;
21 import org.apache.commons.lang3.builder.CompareToBuilder;
22
23 /**
24 * <p>A triple consisting of three elements.</p>
25 *
26 * <p>This class is an abstract implementation defining the basic API.
27 * It refers to the elements as 'left', 'middle' and 'right'.</p>
28 *
29 * <p>Subclass implementations may be mutable or immutable.
30 * However, there is no restriction on the type of the stored objects that may be stored.
31 * If mutable objects are stored in the triple, then the triple itself effectively becomes mutable.</p>
32 *
33 * @param <L> the left element type
34 * @param <M> the middle element type
35 * @param <R> the right element type
36 *
37 * @version $Id: Triple.java 1552635 2013-12-20 13:02:03Z britter $
38 * @since 3.2
39 */
40 public abstract class Triple<L, M, R> implements Comparable<Triple<L, M, R>>, Serializable {
41
42 /** Serialization version */
43 private static final long serialVersionUID = 1L;
44
45 /**
46 * <p>Obtains an immutable triple of from three objects inferring the generic types.</p>
47 *
48 * <p>This factory allows the triple to be created using inference to
49 * obtain the generic types.</p>
50 *
51 * @param <L> the left element type
52 * @param <M> the middle element type
53 * @param <R> the right element type
54 * @param left the left element, may be null
55 * @param middle the middle element, may be null
56 * @param right the right element, may be null
57 * @return a triple formed from the three parameters, not null
58 */
59 public static <L, M, R> Triple<L, M, R> of(final L left, final M middle, final R right) {
60 return new ImmutableTriple<L, M, R>(left, middle, right);
61 }
62
63 //-----------------------------------------------------------------------
64 /**
65 * <p>Gets the left element from this triple.</p>
66 *
67 * @return the left element, may be null
68 */
69 public abstract L getLeft();
70
71 /**
72 * <p>Gets the middle element from this triple.</p>
73 *
74 * @return the middle element, may be null
75 */
76 public abstract M getMiddle();
77
78 /**
79 * <p>Gets the right element from this triple.</p>
80 *
81 * @return the right element, may be null
82 */
83 public abstract R getRight();
84
85 //-----------------------------------------------------------------------
86 /**
87 * <p>Compares the triple based on the left element, followed by the middle element,
88 * finally the right element.
89 * The types must be {@code Comparable}.</p>
90 *
91 * @param other the other triple, not null
92 * @return negative if this is less, zero if equal, positive if greater
93 */
94 @Override
95 public int compareTo(final Triple<L, M, R> other) {
96 return new CompareToBuilder().append(getLeft(), other.getLeft())
97 .append(getMiddle(), other.getMiddle())
98 .append(getRight(), other.getRight()).toComparison();
99 }
100
101 /**
102 * <p>Compares this triple to another based on the three elements.</p>
103 *
104 * @param obj the object to compare to, null returns false
105 * @return true if the elements of the triple are equal
106 */
107 @Override
108 public boolean equals(final Object obj) {
109 if (obj == this) {
110 return true;
111 }
112 if (obj instanceof Triple<?, ?, ?>) {
113 final Triple<?, ?, ?> other = (Triple<?, ?, ?>) obj;
114 return ObjectUtils.equals(getLeft(), other.getLeft())
115 && ObjectUtils.equals(getMiddle(), other.getMiddle())
116 && ObjectUtils.equals(getRight(), other.getRight());
117 }
118 return false;
119 }
120
121 /**
122 * <p>Returns a suitable hash code.</p>
123 *
124 * @return the hash code
125 */
126 @Override
127 public int hashCode() {
128 return (getLeft() == null ? 0 : getLeft().hashCode()) ^
129 (getMiddle() == null ? 0 : getMiddle().hashCode()) ^
130 (getRight() == null ? 0 : getRight().hashCode());
131 }
132
133 /**
134 * <p>Returns a String representation of this triple using the format {@code ($left,$middle,$right)}.</p>
135 *
136 * @return a string describing this object, not null
137 */
138 @Override
139 public String toString() {
140 return new StringBuilder().append('(').append(getLeft()).append(',').append(getMiddle()).append(',')
141 .append(getRight()).append(')').toString();
142 }
143
144 /**
145 * <p>Formats the receiver using the given format.</p>
146 *
147 * <p>This uses {@link java.util.Formattable} to perform the formatting. Three variables may
148 * be used to embed the left and right elements. Use {@code %1$s} for the left
149 * element, {@code %2$s} for the middle and {@code %3$s} for the right element.
150 * The default format used by {@code toString()} is {@code (%1$s,%2$s,%3$s)}.</p>
151 *
152 * @param format the format string, optionally containing {@code %1$s}, {@code %2$s} and {@code %3$s}, not null
153 * @return the formatted string, not null
154 */
155 public String toString(final String format) {
156 return String.format(format, getLeft(), getMiddle(), getRight());
157 }
158
159 }
160
+0
-136
src/main/resources/templates/release-notes.vm less more
0 ## Licensed to the Apache Software Foundation (ASF) under one
1 ## or more contributor license agreements. See the NOTICE file
2 ## distributed with this work for additional information
3 ## regarding copyright ownership. The ASF licenses this file
4 ## to you under the Apache License, Version 2.0 (the
5 ## "License"); you may not use this file except in compliance
6 ## with the License. You may obtain a copy of the License at
7 ##
8 ## http://www.apache.org/licenses/LICENSE-2.0
9 ##
10 ## Unless required by applicable law or agreed to in writing,
11 ## software distributed under the License is distributed on an
12 ## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
13 ## KIND, either express or implied. See the License for the
14 ## specific language governing permissions and limitations
15 ## under the License.
16
17 Apache ${project.name} Package
18 Version ${version}
19 Release Notes
20
21
22 INTRODUCTION:
23
24 This document contains the release notes for the 3.0.1 version of Apache Commons Lang.
25 Commons Lang is a set of utility functions and reusable components that should be of use in any
26 Java environment.
27
28 Lang 3.0 and onwards now targets Java 5.0, making use of features that arrived with Java 5.0 such as generics,
29 variable arguments, autoboxing, concurrency and formatted output.
30
31 For the advice on upgrading from 2.x to 3.x, see the following page:
32
33 http://commons.apache.org/lang/article3_0.html
34
35 ## Hack to improve layout: replace all pairs of spaces with a single new-line
36 ##$release.description.replaceAll(" ", "
37 ##")
38
39 #if ($release.getActions().size() == 0)
40 No changes defined in this version.
41 #else
42 Changes in this version include:
43
44 #if ($release.getActions('add').size() !=0)
45 New features:
46 #foreach($actionItem in $release.getActions('add'))
47 #set($action=$actionItem.getAction())
48 #if ($actionItem.getIssue())
49 #set($issue=$actionItem.getIssue())
50 #else
51 #set($issue="")
52 #end
53 #if ($actionItem.getDueTo())
54 #set($dueto=$actionItem.getDueTo())
55 #else
56 #set($dueto="")
57 #end
58 o#if($!issue != "") $issue: #end ${action} #if($!dueto != "")Thanks to $dueto. #end
59
60 #set($issue="")
61 #set($dueto="")
62 #end
63 #end
64
65 #if ($release.getActions('fix').size() !=0)
66 Fixed Bugs:
67 #foreach($actionItem in $release.getActions('fix'))
68 #set($action=$actionItem.getAction())
69 #if ($actionItem.getIssue())
70 #set($issue=$actionItem.getIssue())
71 #else
72 #set($issue="")
73 #end
74 #if ($actionItem.getDueTo())
75 #set($dueto=$actionItem.getDueTo())
76 #else
77 #set($dueto="")
78 #end
79 o#if($!issue != "") $issue: #end ${action} #if($!dueto != "")Thanks to $dueto. #end
80
81 #set($issue="")
82 #set($dueto="")
83 #end
84 #end
85
86 #if ($release.getActions('update').size() !=0)
87 Changes:
88 #foreach($actionItem in $release.getActions('update'))
89 #set($action=$actionItem.getAction())
90 #if ($actionItem.getIssue())
91 #set($issue=$actionItem.getIssue())
92 #else
93 #set($issue="")
94 #end
95 #if ($actionItem.getDueTo())
96 #set($dueto=$actionItem.getDueTo())
97 #else
98 #set($dueto="")
99 #end
100 o#if($!issue != "") $issue: #end ${action} #if($!dueto != "")Thanks to $dueto. #end
101
102 #set($issue="")
103 #set($dueto="")
104 #end
105 #end
106
107 #if ($release.getActions('remove').size() !=0)
108 Removed:
109 #foreach($actionItem in $release.getActions('remove'))
110 #set($action=$actionItem.getAction())
111 #if ($actionItem.getIssue())
112 #set($issue=$actionItem.getIssue())
113 #else
114 #set($issue="")
115 #end
116 #if ($actionItem.getDueTo())
117 #set($dueto=$actionItem.getDueTo())
118 #else
119 #set($dueto="")
120 #end
121 o#if($!issue != "") $issue: #end ${action} #if($!dueto != "")Thanks to $dueto. #end
122
123 #set($issue="")
124 #set($dueto="")
125 #end
126 #end
127 ## End of main loop
128 #end
129
130 For complete information on ${project.name}, including instructions on how to submit bug reports,
131 patches, or suggestions for improvement, see the Apache ${project.name} website:
132
133 ${project.url}
134
135
+0
-566
src/site/changes/changes.xml less more
0 <?xml version="1.0"?>
1 <!--
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 -->
17 <document>
18 <properties>
19 <title>Commons Lang Changes</title>
20 </properties>
21 <body>
22
23 <release version="3.1" date="unreleased" description="September release">
24 <action type="add" issue="LANG-760">Add API StringUtils.toString(byte[] intput, String charsetName)</action>
25 <action type="update" issue="LANG-758">Add an example with whitespace in StringUtils.defaultIfEmpty</action>
26 <action type="add" issue="LANG-756">Add APIs ClassUtils.isPrimitiveWrapper(Class&lt;?&gt;) and isPrimitiveOrWrapper(Class&lt;?&gt;)</action>
27 <action type="update" issue="LANG-752">Fix createLong() so it behaves like createInteger()</action>
28 <action type="update" issue="LANG-751">Include the actual type in the Validate.isInstance and isAssignableFrom exception messages</action>
29 <action type="fix" issue="LANG-749">Incorrect Bundle-SymbolicName in Manifest</action>
30 <action type="update" issue="LANG-748">Deprecating chomp(String, String)</action>
31 <action type="fix" issue="LANG-746">NumberUtils does not handle upper-case hex: 0X and -0X</action>
32 <action type="fix" issue="LANG-744">StringUtils throws java.security.AccessControlException on Google App Engine</action>
33 <action type="fix" issue="LANG-741">Ant build has wrong component.name</action>
34 <action type="update" issue="LANG-736">CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY</action>
35 <action type="fix" issue="LANG-698">Document that the Mutable numbers don't work as expected with String.format</action>
36 <action type="add" issue="LANG-695">SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system</action>
37 </release>
38
39 <release version="3.0.1" date="2011-08-09" description="August release">
40 <action type="fix" issue="LANG-626">SerializationUtils.clone: Fallback to context classloader if class not found in current classloader.</action>
41 <action type="fix" issue="LANG-727">ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6.</action>
42 <action type="fix" issue="LANG-720">StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes.</action>
43 <action type="fix" issue="LANG-708">StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string.</action>
44 <action type="update" issue="LANG-686">Improve exception message when StringUtils.replaceEachRepeatedly detects recursion.</action>
45 <action type="update" issue="LANG-717">Specify source encoding for Ant build.</action>
46 <action type="add" issue="LANG-721">Complement ArrayUtils.addAll() variants with by-index and by-value removal methods.</action>
47 <action type="add" issue="LANG-726">Add Range&lt;T&gt; Range&lt;T&gt;.intersectionWith(Range&lt;T&gt;).</action>
48 <action type="add" issue="LANG-723">Add mode and median Comparable... methods to ObjectUtils.</action>
49 <action type="add" issue="LANG-722">Add BooleanUtils.and + or varargs methods.</action>
50 <action type="add" issue="LANG-730">EnumSet -&gt; bit vector.</action>
51 <action type="fix" issue="LANG-734">The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character.</action>
52 <action type="update" issue="LANG-735">Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char).</action>
53 <action type="add" issue="LANG-737">Missing method getRawMessage for ContextedException and ContextedRuntimeException.</action>
54 <action type="fix" issue="LANG-738">Use internal Java's Number caches instead creating new objects.</action>
55 </release>
56
57 <release version="3.0" date="2011-07-18" description="Backwards incompatible update of Commons Lang to Java 5">
58 <action type="fix" issue="LANG-720">StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes.</action>
59 <action type="update" issue="LANG-718">build.xml Java 1.5+ updates.</action>
60 <action type="fix" issue="LANG-716">swapCase and *capitalize speedups.</action>
61 <action type="fix" issue="LANG-715">CharSetUtils.squeeze() speedup.</action>
62 <action type="fix" issue="LANG-714">StringUtils doc/comment spelling fixes.</action>
63 <action type="update" issue="LANG-713">Increase test coverage of FieldUtils read methods and tweak javadoc.</action>
64 <action type="fix" issue="LANG-711">Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain).</action>
65 <action type="fix" issue="LANG-710">StringIndexOutOfBoundsException when calling unescapeHtml4("&amp;#03").</action>
66 <action type="fix" issue="LANG-708">StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string.</action>
67 <action type="fix" issue="LANG-703">StringUtils.join throws NPE when toString returns null for one of objects in collection.</action>
68 <action type="add" issue="LANG-697">Add FormattableUtils class.</action>
69 <action type="add">Add ClassUtils.getSimpleName() methods.</action>
70 <action type="add" issue="LANG-692">Add hashCodeMulti varargs method.</action>
71 <action type="remove" issue="LANG-691">Removed DateUtils.UTC_TIME_ZONE.</action>
72 <action type="update" issues="LANG-687">Convert more of the StringUtils API to take CharSequence.</action>
73 <action type="fix" issue="LANG-685">EqualsBuilder synchronizes on HashCodeBuilder.</action>
74 <action type="fix" issue="LANG-428">StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "".</action>
75 <action type="add" issue="LANG-678">Add support for ConcurrentMap.putIfAbsent().</action>
76 <action type="add" issue="LANG-676">Documented potential NPE if auto-boxing occurs for some BooleanUtils methods.</action>
77 <action type="fix" issue="LANG-677">DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour.</action>
78 <action type="add" issue="LANG-610">Extend exception handling in ConcurrentUtils to runtime exceptions.</action>
79 <action type="fix" issue="LANG-624">SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM.</action>
80 <action type="remove" issue="LANG-673">WordUtils.abbreviate() removed.</action>
81 <action type="fix" issue="LANG-672">Doc bug in DateUtils#ceiling.</action>
82 <action type="fix" issue="LANG-646">StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u.</action>
83 <action type="fix" issue="LANG-662">org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k).</action>
84 <action type="fix" issue="LANG-663">org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy.</action>
85 <action type="update" issue="LANG-668">Change ObjectUtils min() &amp; max() functions to use varargs rather than just two parameters.</action>
86 <action type="add" issue="LANG-667">Add a Null-safe compare() method to ObjectUtils.</action>
87 <action type="fix" issue="LANG-664">NumberUtils.isNumber(String) is not right when the String is "1.1L".</action>
88 <action type="fix" issue="LANG-659">EntityArrays typo: {"\u2122", "&amp;minus;"}, // minus sign, U+2212 ISOtech.</action>
89 <action type="fix" issue="LANG-658">Some Entitys like &amp;Ouml; are not matched properly against its ISO8859-1 representation.</action>
90 <action type="fix" issue="LANG-656">Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect.</action>
91 <action type="add" issue="LANG-655">Add StringUtils.defaultIfBlank().</action>
92 <action type="add" issue="LANG-653">Provide a very basic ConcurrentInitializer implementation.</action>
93 <action type="add" issue="LANG-609">Support lazy initialization using atomic variables.</action>
94 <action type="add" issue="LANG-482">Enhance StrSubstitutor to support nested ${var-${subvr}} expansion.</action>
95 <action type="add" issue="LANG-644">Provide documentation about the new concurrent package.</action>
96 <action type="fix" issue="LANG-629">Charset may not be threadsafe, because the HashSet is not synch.</action>
97 <action type="fix" issue="LANG-617">StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters.</action>
98 <action type="add" issue="LANG-614">StringUtils.endsWithAny method.</action>
99 <action type="add" issue="LANG-651">Add AnnotationUtils.</action>
100 <action type="add" issue="LANG-649">BooleanUtils.toBooleanObject to support single character input.</action>
101 <action type="fix" issue="LANG-645">FastDateFormat.format() outputs incorrect week of year because locale isn't respected.</action>
102 <action type="fix" issue="LANG-596">StrSubstitutor should also handle the default properties of a java.util.Properties class.</action>
103 <action type="fix" issue="LANG-643">Javadoc StringUtils.left() claims to throw on negative len, but doesn't.</action>
104 <action type="add" issue="LANG-640">Add normalizeSpace to StringUtils.</action>
105 <action type="fix" issue="LANG-638">NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in.</action>
106 <!-- 3.0 beta below here -->
107 <action>NOTE: The below were included in the Commons Lang 3.0-beta release.</action>
108 <action type="update" issues="LANG-510">Convert StringUtils API to take CharSequence.</action>
109 <action type="update">Push down WordUtils to "text" sub-package.</action>
110 <action type="add" issue="LANG-610">Extend exception handling in ConcurrentUtils to runtime exceptions.</action>
111 <action type="fix" issue="LANG-608">Some StringUtils methods should take an int character instead of char to use String API features.</action>
112 <action type="fix" issue="LANG-606">EqualsBuilder causes StackOverflowException.</action>
113 <action type="update" issue="LANG-605">DefaultExceptionContext overwrites values in recursive situations.</action>
114 <action type="fix" issue="LANG-602">ContextedRuntimeException no longer an 'unchecked' exception.</action>
115 <action type="add" issue="LANG-601">Add Builder Interface / Update Builders to Implement It.</action>
116 <action type="fix" issue="LANG-600">Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr).</action>
117 <action type="update" issue="LANG-599">ClassUtils.getClass(): Allow Dots as Inner Class Separators.</action>
118 <action type="add" issue="LANG-594">DateUtils equal &amp; compare functions up to most significant field.</action>
119 <action type="remove" issue="LANG-590">Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int).</action>
120 <action type="add" issue="LANG-588">Create a basic Pair&lt;L, R&gt; class.</action>
121 <action type="fix" issue="LANG-585">exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable.</action>
122 <action type="add" issue="LANG-582">Provide an implementation of the ThreadFactory interface.</action>
123 <action type="update" issue="LANG-579">Add new Validate methods.</action>
124 <action type="fix" issue="LANG-571">ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException.</action>
125 <action type="update" issue="LANG-570">Do the test cases really still require main() and suite() methods?.</action>
126 <action type="fix" issue="LANG-568">@SuppressWarnings("unchecked") is used too generally.</action>
127 <action type="fix" issue="LANG-564">Improve StrLookup API documentation.</action>
128 <action type="update" issue="LANG-563">Change Java package name.</action>
129 <action type="update" issue="LANG-562">Change Maven groupId.</action>
130 <action type="add" issue="LANG-560">New TimedSemaphore class.</action>
131 <action type="add" issue="LANG-559">Added validState validation method.</action>
132 <action type="add" issue="LANG-559">Added isAssignableFrom and isInstanceOf validation methods.</action>
133 <action type="add" issue="LANG-553">Add TypeUtils class to provide utility code for working with generic types.</action>
134 <action type="update" issue="LANG-551">Replace Range classes with generic version.</action>
135 <action type="update" issue="LANG-548">Use Iterable on API instead of Collection.</action>
136 <action type="add" issue="LANG-546">Add methods to Validate to check whether the index is valid for the array/list/string.</action>
137 <action type="add" issue="LANG-545">Add ability to create a Future for a constant.</action>
138 <action type="update" issue="LANG-541">Replace StringBuffer with StringBuilder.</action>
139 <action type="update" issue="LANG-540">Make NumericEntityEscaper immutable.</action>
140 <action type="update" issue="LANG-539">Compile commons.lang for CDC 1.1/Foundation 1.1.</action>
141 <action type="add" issue="LANG-537">Add ArrayUtils.toArray to create generic arrays.</action>
142 <action type="add" issue="LANG-533">Validate: support for validating blank strings.</action>
143 <action type="add" issue="LANG-529">Add a concurrent package.</action>
144 <action type="update" issue="LANG-528">Mutable classes should implement an appropriately typed Mutable interface.</action>
145 <action type="update" issue="LANG-513">Better EnumUtils.</action>
146 <action type="update" issue="LANG-507">StringEscapeUtils.unescapeJava should support \u+ notation.</action>
147 <action type="update" issue="LANG-505">Rewrite StringEscapeUtils.</action>
148 <action type="update" issue="LANG-504">bring ArrayUtils.isEmpty to the generics world.</action>
149 <action type="add" issue="LANG-501">Add support for background initialization.</action>
150 <action type="add" issue="LANG-499">Add support for the handling of ExecutionExceptions.</action>
151 <action type="add" issue="LANG-498">Add StringEscapeUtils.escapeText() methods.</action>
152 <action type="add" issue="LANG-497">Addition of ContextedException and ContextedRuntimeException.</action>
153 <action type="add" issue="LANG-496">A generic implementation of the Lazy initialization pattern.</action>
154 <action type="remove" issue="LANG-493">Remove code that does not hold enough value to remain.</action>
155 <action type="remove" issue="LANG-492">Remove code handled now by the JDK.</action>
156 <action type="add" issue="LANG-482">StrSubstitutor now supports substitution in variable names.</action>
157 <action type="fix" issue="LANG-481">Possible race-conditions in hashCode of the range classes.</action>
158 <action type="fix" issue="LANG-480">StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters.</action>
159 <action type="update" issue="LANG-479">Document where in SVN trunk is.</action>
160 <action type="fix" issue="LANG-478">StopWatch does not resist to system time changes.</action>
161 <action type="fix" issue="LANG-474">Fixes for thread safety.</action>
162 <action type="update" issue="LANG-458">Refactor Validate.java to eliminate code redundancy.</action>
163 <action type="fix" issue="LANG-448">Lower Ascii Characters don't get encoded by Entities.java.</action>
164 <action type="add" issue="LANG-444">StringUtils.emptyToNull.</action>
165 <action type="fix" issue="LANG-439">StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20).</action>
166 <action type="remove" issue="LANG-438">Remove @deprecateds.</action>
167 <action type="add" issue="LANG-435">Add ClassUtils.isAssignable() variants with autoboxing.</action>
168 <action type="update" issue="LANG-424">Improve Javadoc for StringUtils class.</action>
169 <action type="fix" issue="LANG-418">Javadoc incorrect for StringUtils.endsWithIgnoreCase.</action>
170 <action type="update" issue="LANG-396">Investigate for vararg usages.</action>
171 <action type="fix" issue="LANG-468">JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder).</action>
172 <action type="add" issue="LANG-386">LeftOf/RightOfNumber in Range convenience methods necessary.</action>
173 <action type="fix" issue="LANG-369">ExceptionUtils not thread-safe.</action>
174 <action type="add" issue="LANG-358">ObjectUtils.coalesce.</action>
175 <action type="update" issue="LANG-355">StrBuilder should implement CharSequence and Appendable.</action>
176 <action type="fix" issue="LANG-339">StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanes, etc.</action>
177 <action type="update" issue="LANG-336">Finally start using generics.</action>
178 <action type="fix" issue="LANG-302">StrBuilder does not implement clone().</action>
179 <action type="update" issue="LANG-290">EnumUtils for JDK 5.0.</action>
180 <action type="add" issue="LANG-285">Wish : method unaccent.</action>
181 <action type="add" issue="LANG-276">MutableBigDecimal and MutableBigInteger.</action>
182 <action type="fix" issue="LANG-66">StringEscaper.escapeXml() escapes characters &gt; 0x7f.</action>
183 <action type="fix" issue="LANG-11">Depend on JDK 1.5+.</action>
184 </release>
185
186 <release version="2.6" date="2011-01-16" description="Bug Fixes/Enhancements for the 2.6 release (requires minimum of Java 1.3)">
187 <action type="update" issue="LANG-633">BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String).</action>
188 <action type="update" issue="LANG-599">ClassUtils: allow Dots as Inner Class Separators in getClass().</action>
189 <action type="add" issue="LANG-594">DateUtils: equal and compare functions up to most significant field.</action>
190 <action type="add" issue="LANG-632">DateUtils: provide a Date to Calendar convenience method.</action>
191 <action type="add" issue="LANG-576">ObjectUtils: add clone methods to ObjectUtils.</action>
192 <action type="add" issue="LANG-667">ObjectUtils: add a Null-safe compare() method.</action>
193 <action type="add" issue="LANG-670">ObjectUtils: add notEqual() method.</action>
194 <action type="add" issue="LANG-302">StrBuilder: implement clone() method.</action>
195 <action type="add" issue="LANG-640">StringUtils: add a normalizeSpace() method.</action>
196 <action type="add" issue="LANG-614">StringUtils: add endsWithAny() method.</action>
197 <action type="add" issue="LANG-655">StringUtils: add defaultIfBlank() method.</action>
198 <action type="add" issue="LANG-596">StrSubstitutor: add a replace(String, Properties) variant.</action>
199 <action type="add" issue="LANG-482">StrSubstitutor: support substitution in variable names.</action>
200 <action type="update" issue="LANG-669">Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue.</action>
201 <action type="fix" issue="LANG-629">CharSet: make the underlying set synchronized.</action>
202 <action type="fix" issue="LANG-635">CompareToBuilder: fix passing along compareTransients to the reflectionCompare method.</action>
203 <action type="fix" issue="LANG-636">ExtendedMessageFormat doesn't override equals(Object).</action>
204 <action type="fix" issue="LANG-645">FastDateFormat: fix to properly include the locale when formatting a Date.</action>
205 <action type="fix" issue="LANG-638">NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in.</action>
206 <action type="fix" issue="LANG-607">StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly.</action>
207 <action type="fix" issue="LANG-624">SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM.</action>
208 <action type="fix" issue="BEANUTILS-381">MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading.</action>
209 <action type="update" issue="LANG-600">Javadoc is incorrect for lastIndexOf() method.</action>
210 <action type="update" issue="LANG-628">Javadoc for HashCodeBuilder.append(boolean) does not match implementation.</action>
211 <action type="update" issue="LANG-643">Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't.</action>
212 <action type="update" issue="LANG-370">Javadoc - document thread safety.</action>
213 <action type="update" issue="LANG-623">Test for StringUtils replaceChars() icelandic characters.</action>
214 </release>
215
216 <release version="2.5" date="2010-02-25" description="">
217 <action type="add" issue="LANG-583">ArrayUtils - add isNotEmpty() methods.</action>
218 <action type="add" issue="LANG-534">ArrayUtils - add nullToEmpty() methods.</action>
219 <action type="add" issue="LANG-454">CharRange - provide an iterator that lets you walk the chars in the range.</action>
220 <action type="add" issue="LANG-514">CharRange - add more readable static builder methods.</action>
221 <action type="add">ClassUtils - new isAssignable() methods with autoboxing.</action>
222 <action type="add" issue="LANG-535">ClassUtils - add support to getShortClassName and getPackageName for arrays.</action>
223 <action type="add" issue="LANG-434">DateUtils - add ceiling() method.</action>
224 <action type="add" issue="LANG-486">DateUtils - add parseDateStrictly() method.</action>
225 <action type="add" issue="LANG-466">EqualsBuilder - add reset() method.</action>
226 <action type="add" issue="LANG-461">NumberUtils - add toByte() and toShort() methods.</action>
227 <action type="add" issue="LANG-522">Mutable numbers - add string constructors.</action>
228 <action type="add">MutableBoolean - add toBoolean(), isTrue() and isFalse() methods.</action>
229 <action type="add" issue="LANG-422">StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty.</action>
230 <action type="add" issue="LANG-555">SystemUtils - add IS_OS_WINDOWS_7 constant.</action>
231 <action type="add" issue="LANG-554">SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7.</action>
232 <action type="add" issue="LANG-405">StringUtils - add abbreviateMiddle() method.</action>
233 <action type="add" issue="LANG-569">StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods.</action>
234 <action type="add" issue="LANG-471">StringUtils - add isAllUpperCase() and isAllLowerCase() methods.</action>
235 <action type="add" issue="LANG-469">StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method.</action>
236 <action type="add" issue="LANG-348">StringUtils - add repeat() method.</action>
237 <action type="add" issue="LANG-445">StringUtils - add startsWithAny() method.</action>
238 <action type="add" issue="LANG-430">StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods.</action>
239 <action type="add" issue="LANG-416">New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils.</action>
240 <action type="fix" issue="LANG-567">ArrayUtils - addAll() does not handle mixed types very well.</action>
241 <action type="fix" issue="LANG-494">CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread.</action>
242 <action type="fix" issue="LANG-500">ClassUtils - improving performance of getAllInterfaces.</action>
243 <action type="fix" issue="LANG-587">ClassUtils - toClass() throws NullPointerException on null array element.</action>
244 <action type="fix" issue="LANG-530">DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat.</action>
245 <action type="fix" issue="LANG-440">DateUtils - round() doesn't work correct for Calendar.AM_PM.</action>
246 <action type="fix" issue="LANG-443">DateUtils - improve tests.</action>
247 <action type="fix" issue="LANG-204">Entities - multithreaded initialization.</action>
248 <action type="fix" issue="LANG-506">Entities - missing final modifiers; thread-safety issues.</action>
249 <action type="fix" issue="LANG-76">EnumUtils - getEnum() doesn't work well in 1.5+.</action>
250 <action type="fix" issue="LANG-584">ExceptionUtils - use immutable lock target.</action>
251 <action type="fix" issue="LANG-477">ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes.</action>
252 <action type="fix" issue="LANG-538">FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state.</action>
253 <action type="fix" issue="LANG-547">FastDateFormat - Remove unused field.</action>
254 <action type="fix" issue="LANG-511">LocaleUtils - Initialization of available locales in LocaleUtils can be deferred.</action>
255 <action type="fix" issue="LANG-457">NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in.</action>
256 <action type="fix" issue="LANG-521">NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'.</action>
257 <action type="fix" issue="LANG-432">StringUtils - improve handling of case-insensitive Strings.</action>
258 <action type="fix" issue="LANG-552">StringUtils - replaceEach() no longer NPEs when null appears in the last String[].</action>
259 <action type="fix" issue="LANG-460">StringUtils - correct JavaDocs for startsWith() and startsWithIgnoreCase().</action>
260 <action type="fix" issue="LANG-421">StringEscapeUtils - escapeJava() escapes '/' characters.</action>
261 <action type="fix" issue="LANG-450">StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null.</action>
262 <action type="fix" issue="LANG-419">WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length.</action>
263 <action type="fix" issue="LANG-523">StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity.</action>
264 <action type="fix" issue="LANG-575">Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List.</action>
265 <action type="fix" issue="LANG-467">EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder.</action>
266 <action type="fix" issue="LANG-574">HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks.</action>
267 <action type="fix" issue="LANG-520">HashCodeBuilder - Changing the hashCode() method to return toHashCode().</action>
268 <action type="fix" issue="LANG-459">HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes.</action>
269 <action type="fix" issue="LANG-586">HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments.</action>
270 <action type="fix" issue="LANG-487">ToStringBuilder - make default style thread-safe.</action>
271 <action type="fix" issue="LANG-472">RandomUtils - nextLong() always produces even numbers.</action>
272 <action type="fix" issue="LANG-592">RandomUtils - RandomUtils tests are failing frequently.</action>
273 </release>
274
275 <release version="2.4" date="2008-03-18" description="">
276 <action type="add" issue="LANG-322">ClassUtils.getShortClassName(String) inefficient.</action>
277 <action type="add" issue="LANG-269">Shouldn't Commons Lang's StringUtils have a "common" string method?.</action>
278 <action type="fix" issue="LANG-368">FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change.</action>
279 <action type="add" issue="LANG-402">OSGi-ify Lang.</action>
280 <action type="fix" issue="LANG-412">StrBuilder appendFixedWidth does not handle nulls.</action>
281 <action type="fix" issue="LANG-380">infinite loop in Fraction.reduce when numerator == 0.</action>
282 <action type="fix" issue="LANG-367">FastDateFormat thread safety.</action>
283 <action type="add" issue="LANG-298">ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array.</action>
284 <action type="fix" issue="LANG-328">LocaleUtils.toLocale() rejects strings with only language+variant.</action>
285 <action type="fix" issue="LANG-334">Enum is not thread-safe.</action>
286 <action type="fix" issue="LANG-365">BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException.</action>
287 <action type="add" issue="LANG-333">ArrayUtils.toClass.</action>
288 <action type="fix" issue="LANG-360">Why does appendIdentityToString return null?.</action>
289 <action type="fix" issue="LANG-381">NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN.</action>
290 <action type="fix" issue="LANG-346">Dates.round() behaves incorrectly for minutes and seconds.</action>
291 <action type="add" issue="LANG-407">StringUtils.length(String) returns null-safe length.</action>
292 <action type="add" issue="LANG-180">adding a StringUtils.replace method that takes an array or List of replacement strings.</action>
293 <action type="add" issue="LANG-383">Adding functionality to DateUtils to allow direct setting of various fields.</action>
294 <action type="add" issue="LANG-374">Add escaping for CSV columns to StringEscapeUtils.</action>
295 <action type="add" issue="LANG-326">StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods.</action>
296 <action type="add" issue="LANG-351">Extension to ClassUtils: Obtain the primitive class from a wrapper.</action>
297 <action type="fix" issue="LANG-399">Javadoc bugs - cannot find object.</action>
298 <action type="add" issue="LANG-345">Optimize HashCodeBuilder.append(Object).</action>
299 <action type="fix" issue="LANG-385">http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete.</action>
300 <action type="fix" issue="LANG-410">Ambiguous / confusing names in StringUtils replace* methods.</action>
301 <action type="add" issue="LANG-257">Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils.</action>
302 <action type="add" issue="LANG-356">Add getStartTime to StopWatch.</action>
303 <action type="add" issue="LANG-377">Perhaps add containsAny() methods?.</action>
304 <action type="fix" issue="LANG-353">Javadoc Example for EqualsBuilder is questionable.</action>
305 <action type="fix" issue="LANG-393">EqualsBuilder don't compare BigDecimals correctly.</action>
306 <action type="add" issue="LANG-192">Split camel case strings.</action>
307 <action type="add" issue="LANG-404">Add Calendar flavour format methods to DateFormatUtils.</action>
308 <action type="add" issue="LANG-379">Calculating A date fragment in any time-unit.</action>
309 <action type="add" issue="LANG-413">Memory usage improvement for StringUtils#getLevenshteinDistance().</action>
310 <action type="add" issue="LANG-362">Add ExtendedMessageFormat to org.apache.commons.lang.text.</action>
311 <action type="fix" issue="LANG-363">StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly.</action>
312 <action type="add" issue="LANG-321">Add toArray() method to IntRange and LongRange classes.</action>
313 <action type="add" issue="LANG-375">add SystemUtils.IS_OS_WINDOWS_VISTA field.</action>
314 <action type="add" issue="LANG-329">Pointless synchronized in ThreadLocal.initialValue should be removed.</action>
315 <action type="add" issue="LANG-371">ToStringStyle javadoc should show examples of styles.</action>
316 <action type="fix" issue="LANG-364">Documentation bug for ignoreEmptyTokens accessors in StrTokenizer.</action>
317 <action type="fix" issue="LANG-361">BooleanUtils toBooleanObject javadoc does not match implementation.</action>
318 <action type="add" issue="LANG-338">truncateNicely method which avoids truncating in the middle of a word.</action>
319 </release>
320
321 <release version="2.3" date="2007-02-13" description="">
322 <action type="fix" issue="LANG-262">Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions.</action>
323 <action type="add" issue="LANG-289">NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing.</action>
324 <action type="add" issue="LANG-291">Null-safe comparison methods for finding most recent / least recent dates.</action>
325 <action type="fix" issue="LANG-315">StopWatch: suspend() acts as split(), if followed by stop().</action>
326 <action type="fix" issue="LANG-294">StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException.</action>
327 <action type="fix" issue="LANG-299">Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException.</action>
328 <action type="fix" issue="LANG-69"> ToStringBuilder throws StackOverflowError when an Object cycle exists.</action>
329 <action type="add" issue="LANG-282">Create more tests to test out the +=31 replacement code in DurationFormatUtils.</action>
330 <action type="fix" issue="LANG-295">StrBuilder contains usages of thisBuf.length when they should use size.</action>
331 <action type="add" issue="LANG-258">Enum JavaDoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui.</action>
332 <action type="fix" issue="LANG-313">Wrong behavior of Entities.unescape.</action>
333 <action type="fix" issue="LANG-300">NumberUtils.createNumber throws NumberFormatException for one digit long.</action>
334 <action type="fix" issue="LANG-304">NullPointerException in isAvailableLocale(Locale).</action>
335 <action type="fix" issue="LANG-303">FastDateFormat.mRules is not transient or serializable.</action>
336 <action type="add" issue="LANG-268">StringUtils.join should allow you to pass a range for it (so it only joins a part of the array).</action>
337 <action type="fix" issue="LANG-102">Refactor Entities methods.</action>
338 <action type="fix" issue="LANG-314">Tests fail to pass when building with Maven 2.</action>
339 <action type="fix" issue="LANG-281">DurationFormatUtils returns wrong result.</action>
340 <action type="fix" issue="LANG-292">unescapeXml("&amp;12345678;") should be "&amp;12345678;".</action>
341 <action type="add" issue="LANG-287">Optimize StringEscapeUtils.unescapeXml(String).</action>
342 <action type="add" issue="LANG-310">BooleanUtils isNotTrue/isNotFalse.</action>
343 <action type="add" issue="LANG-306">Extra StrBuilder methods.</action>
344 <action type="add" issue="LANG-275">Add a pair of StringUtils.substringsBetween;String[] methods.</action>
345 <action type="fix" issue="LANG-279">HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle.</action>
346 <action type="add" issue="LANG-266">Wish for StringUtils.join(Collection, *).</action>
347 </release>
348
349 <release version="2.2" date="2006-10-04" description="">
350 <action type="fix" issue="LANG-45">StrBuilderTest#testReplaceStringString fails.</action>
351 <action type="fix" issue="LANG-42">EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null.</action>
352 <action type="fix" issue="LANG-286">Serialization - not backwards compatible.</action>
353 <action type="fix" issue="LANG-50"> Replace Clover with Cobertura.</action>
354 <action type="fix" issue="LANG-259">ValuedEnum.compareTo(Object other) not typesafe - it easily could be...</action>
355 <action type="fix" issue="LANG-271">LocaleUtils test fails under Mustang.</action>
356 <action type="fix" issue="LANG-2">javadoc example for StringUtils.splitByWholeSeparator incorrect.</action>
357 <action type="fix" issue="LANG-3">PADDING array in StringUtils overflows on '\uffff'.</action>
358 <action type="fix" issue="LANG-10">ClassUtils.primitiveToWrapper and Void.</action>
359 <action type="fix" issue="LANG-37">unit test for org.apache.commons.lang.text.StrBuilder.</action>
360 <action type="fix" issue="LANG-59">DateUtils.truncate method is buggy when dealing with DST switching hours.</action>
361 <action type="fix" issue="LANG-100">RandomStringUtils.random() family of methods create invalid Unicode sequences.</action>
362 <action type="fix" issue="LANG-106">StringUtils#getLevenshteinDistance() performance is sub-optimal.</action>
363 <action type="fix" issue="LANG-112">Wrong length check in StrTokenizer.StringMatcher.</action>
364 <action type="fix" issue="LANG-105">ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable.</action>
365 <action type="fix" issue="LANG-117">FastDateFormat: wrong format for date "01.01.1000".</action>
366 <action type="fix" issue="LANG-123">Unclear javadoc for DateUtils.iterator().</action>
367 <action type="fix" issue="LANG-130">Memory "leak" in StringUtils.</action>
368 <action type="add" issue="LANG-260">StringEscapeUtils should expose escape*() methods taking Writer argument.</action>
369 <action type="fix" issue="LANG-141">Fraction.toProperString() returns -1/1 for -1.</action>
370 <action type="fix" issue="LANG-152">DurationFormatUtils.formatDurationWords "11 &lt;unit&gt;s" gets converted to "11 &lt;unit&gt;".</action>
371 <action type="fix" issue="LANG-148">Performance modifications on StringUtils.replace.</action>
372 <action type="fix" issue="LANG-150">StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand.</action>
373 <action type="fix" issue="LANG-140">DurationFormatUtils.formatPeriod() returns the wrong result.</action>
374 <action type="add" issue="LANG-186">Request for MutableBoolean implementation.</action>
375 <action type="add" issue="LANG-198">New method for EqualsBuilder.</action>
376 <action type="add" issue="LANG-212">New ExceptionUtils method setCause().</action>
377 <action type="add" issue="LANG-217">Add Mutable&lt;Type&gt; to&lt;Type&gt;() methods.</action>
378 <action type="add" issue="LANG-216">Provides a Class.getPublicMethod which returns public invocable Method.</action>
379 <action type="add" issue="LANG-226">Using ReflectionToStringBuilder and excluding secure fields.</action>
380 <action type="add" issue="LANG-194">add generic add method to DateUtils.</action>
381 <action type="add" issue="LANG-220">Tokenizer Enhancements: reset input string, static CSV/TSV factories.</action>
382 <action type="add" issue="LANG-242">Trivial cleanup of javadoc in various files.</action>
383 <action type="add" issue="LANG-246">CompositeFormat.</action>
384 <action type="add" issue="LANG-250">Performance boost for RandomStringUtils.</action>
385 <action type="add" issue="LANG-254">Enhanced Class.forName version.</action>
386 <action type="add" issue="LANG-263">Add StringUtils.containsIgnoreCase(...).</action>
387 <action type="add" issue="LANG-267">Support char array converters on ArrayUtils.</action>
388 <action type="fix" issue="LANG-25">DurationFormatUtils.formatDurationISO() javadoc is missing T in duration string between date and time part.</action>
389 <action type="fix" issue="LANG-272">Minor build and checkstyle changes.</action>
390 <action type="fix" issue="LANG-277">Javadoc errors on StringUtils.splitPreserveAllTokens(String, char).</action>
391 <action type="fix" issue="LANG-122">EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &amp;apos;.</action>
392 <action type="add" issue="LANG-161">Add methods and tests to StrBuilder.</action>
393 <action type="add" issue="LANG-162">replace() length calculation improvement.</action>
394 <action type="add" issue="LANG-166">New interpolation features.</action>
395 <action type="add" issue="LANG-169">Implementation of escape/unescapeHtml methods with Writer.</action>
396 <action type="add" issue="LANG-176">CompareToBuilder excludeFields for reflection method.</action>
397 <action type="add" issue="LANG-159">Add WordUtils.getInitials(String).</action>
398 <action type="fix" issue="LANG-261">Error in an example in the javadoc of the StringUtils.splitPreserveAllTokens() method.</action>
399 <action type="fix" issue="LANG-264">ToStringBuilder/HashCodeBuilder javadoc code examples.</action>
400 <action type="fix" issue="LANG-265">Cannot build tests from latest SVN.</action>
401 <action type="add" issue="LANG-270">minor javadoc improvements for StringUtils.stripXxx() methods.</action>
402 <action type="fix" issue="LANG-278">javadoc for StringUtils.removeEnd is incorrect.</action>
403 <action type="fix" issue="LANG-127">Minor tweak to fix of bug # 26616.</action>
404 </release>
405
406 <release version="2.1" date="2005-06-13" description="">
407 <action type="fix" issue="LANG-103">make optional parameters in FastDateFormat really optional.</action>
408 <action type="fix" issue="LANG-149">Nestable.indexOfThrowable(Class) uses Class.equals() to match.</action>
409 <action type="fix" issue="LANG-30">buffer under/overrun on Strings.strip, stripStart &amp; stripEnd.</action>
410 <action type="fix" issue="LANG-19">ToStringStyle.setArrayEnd(String) doesn't replace null with empty string.</action>
411 <action type="fix" issue="LANG-80">New class proposal: CharacterEncoding.</action>
412 <action type="fix" issue="LANG-43">SystemUtils fails init on HP-UX.</action>
413 <action type="fix" issue="LANG-134">javadoc - 'four basic XML entities' should be 5 (apos is missing).</action>
414 <action type="fix" issue="LANG-156">o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0.</action>
415 <action type="fix" issue="LANG-131">StringEscapeUtils.unescapeHtml() doesn't handle an empty entity.</action>
416 <action type="fix" issue="LANG-6">EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class.</action>
417 <action type="fix" issue="LANG-33">Method enums.Enum.equals(Object o) doesn't work correctly.</action>
418 <action type="fix" issue="LANG-31">ExceptionUtils.addCauseMethodName(String) does not check for duplicates.</action>
419 <action type="fix" issue="LANG-136">Make StopWatch validate state transitions.</action>
420 <action type="fix" issue="LANG-124">enum package is not compatible with 1.5 jdk.</action>
421 <action type="fix" issue="LANG-128">WordUtils capitalizeFully() throws a null pointer exception.</action>
422 <action type="fix" issue="LANG-138">ValuedEnum.</action>
423 <action type="fix" issue="LANG-133">parseDate class from HttpClient's DateParser class.</action>
424 <action type="fix" issue="LANG-62">ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension.</action>
425 <action type="fix" issue="LANG-57">ClassCastException in Enum.equals(Object).</action>
426 <action type="fix" issue="LANG-107">FastDateFormat year bug.</action>
427 <action type="fix" issue="LANG-77">unbalanced ReflectionToStringBuilder.</action>
428 <action type="fix" issue="LANG-86">FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation.</action>
429 <action type="fix" issue="LANG-79">ReflectionToStringBuilder.toString(null) throws exception by design.</action>
430 <action type="fix" issue="LANG-126">Make ClassUtils methods null-safe and not throw an IAE.</action>
431 <action type="fix" issue="LANG-5">StringUtils.split ignores empty items.</action>
432 <action type="fix" issue="LANG-144">EqualsBuilder.append(Object[], Object[]) throws NPE.</action>
433 <action type="fix" issue="LANG-74">ArrayUtils.addAll doesn't always return new array.</action>
434 <action type="fix" issue="LANG-81">Enum.equals does not handle different class loaders.</action>
435 <action type="fix" issue="LANG-27">Add SystemUtils.AWT_TOOLKIT and others.</action>
436 <action type="fix" issue="LANG-14">Throwable cause for NotImplementedException.</action>
437 <action type="fix" issue="LANG-28">ClassUtils.primitivesToWrappers method.</action>
438 <action type="fix" issue="LANG-120">public static boolean DateUtils.equals(Date dt1, Date dt2) ?.</action>
439 <action type="fix" issue="LANG-7">Documentation error in StringUtils.replace.</action>
440 <action type="fix" issue="LANG-125">DateUtils constants should be long.</action>
441 <action type="fix" issue="LANG-13">DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'.</action>
442 <action type="fix" issue="LANG-118">StringEscapeUtils.unescapeHtml() doesn't handle hex entities.</action>
443 <action type="fix" issue="LANG-99">new StringUtils.replaceChars behaves differently from old CharSetUtils.translate.</action>
444 <action type="fix" issue="LANG-41">last substring returned by StringUtils.split( String, String, int ) is too long.</action>
445 <action type="fix" issue="LANG-119">Can't subclass EqualsBuilder because isEquals is private.</action>
446 <action type="fix" issue="LANG-158">new StringUtils.split methods that split on the whole separator string.</action>
447 <action type="add" issue="LANG-172">New method for converting a primitive Class to its corresponding wrapper Class.</action>
448 <action type="add" issue="LANG-222">Add convenience format(long) methods to FastDateFormat.</action>
449 <action type="fix" issue="LANG-116">Enum's outer class may not be loaded for EnumUtils.</action>
450 <action type="add" issue="LANG-219">WordUtils.capitalizeFully(String str) should take a delimiter.</action>
451 <action type="add" issue="LANG-183">Make javadoc crosslinking configurable.</action>
452 <action type="fix" issue="LANG-82">Minor javadoc fixes for StringUtils.contains(String, String).</action>
453 <action type="fix" issue="LANG-32">Error in JavaDoc for StringUtils.chomp(String, String).</action>
454 <action type="fix" issue="LANG-95">StringUtils.defaultString: Documentation error.</action>
455 <action type="add" issue="LANG-233">Add hashCode-support to class ObjectUtils.</action>
456 <action type="add" issue="LANG-202">add another "known method" to ExceptionUtils.</action>
457 <action type="add" issue="LANG-235">Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES.</action>
458 <action type="fix" issue="LANG-24">DateUtils.truncate oddity at the far end of the Date spectrum.</action>
459 <action type="add" issue="LANG-232">add getLength() method to ArrayUtils.</action>
460 <action type="add" issue="LANG-171">Validate.java: fixes comment skew, removes unused loop counter.</action>
461 <action type="add" issue="LANG-179">StringUtils.isAsciiPrintable().</action>
462 <action type="add" issue="LANG-167">ExceptionUtils: new getCause() methodname (for tomcat-exception).</action>
463 <action type="fix" issue="LANG-85">fixes 75 typos.</action>
464 <action type="add" issue="LANG-230">mutable numbers.</action>
465 <action type="add" issue="LANG-191">Javadoc fixes for ClassUtils.</action>
466 <action type="add" issue="LANG-184">Add StringUtils.nIndexOf?.</action>
467 <action type="fix" issue="LANG-135">Javadoc fixes for CharSetUtils.</action>
468 <action type="fix" issue="LANG-154">Remove redundant check for null separator in StringUtils#join.</action>
469 <action type="add" issue="LANG-247">Class and Package Comparators for ClassUtils.</action>
470 <action type="add" issue="LANG-256">add remove methods to ArrayUtils.</action>
471 <action type="add" issue="LANG-185">WordUtils capitalize improvement.</action>
472 <action type="add" issue="LANG-173">add isEmpty method to ArrayUtils.</action>
473 <action type="add" issue="LANG-168">lang.math.Fraction class deficiencies.</action>
474 <action type="add" issue="LANG-207">Add methods to ArrayUtils: add at end and insert-like ops.</action>
475 <action type="add" issue="LANG-239">Add SystemUtils methods for directory properties.</action>
476 <action type="add" issue="LANG-189">Add method that validates Collection elements are a certain type.</action>
477 <action type="add" issue="LANG-224">elapsed time formatting utility method.</action>
478 </release>
479
480 <release version="2.0" date="2003-09-02" description="">
481 <action type="fix" issue="LANG-20">Infinite loop in ToStringBuilder.reflectionToString for inner classes.</action>
482 <action type="fix" issue="LANG-75">NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08.</action>
483 <action type="fix" issue="LANG-38">Rationalize StringUtils slice functions.</action>
484 <action type="fix" issue="LANG-53">SystemUtils.IS_OS_OS2 Javadoc is wrong.</action>
485 <action type="fix" issue="LANG-142">A small, but important javadoc fix for Fraction proper whole and numerator.</action>
486 <action type="fix" issue="LANG-70">Adding tolerance to double[] search methods in ArrayUtils.</action>
487 <action type="fix" issue="LANG-9">lang.builder classes javadoc edits (mostly typo fixes).</action>
488 <action type="fix" issue="LANG-63">StringUtils javadoc and test enhancements.</action>
489 <action type="fix" issue="LANG-132">SystemUtils.IS_OS_*, IS_JAVA_* are always false.</action>
490 <action type="fix" issue="LANG-143">Improve util.Validate tests.</action>
491 <action type="fix" issue="LANG-155">maven-beta10 checkstyle problem.</action>
492 <action type="fix" issue="LANG-147">StringUtils.chopNewLine - StringIndexOutOfBoundsException.</action>
493 <action type="fix" issue="LANG-73">ToStringBuilder doesn't work well in subclasses.</action>
494 <action type="fix" issue="LANG-48">static option for reversing the stacktrace.</action>
495 <action type="fix" issue="LANG-87">NullPointerException in CompareToBuilder.</action>
496 <action type="fix" issue="LANG-84">RandomStringUtils.randomAlpha methods omit 'z'.</action>
497 <action type="fix" issue="LANG-129">test.time fails in Japanese (non-us) locale.</action>
498 <action type="fix" issue="LANG-94">NumberUtils.isNumber allows illegal trailing characters.</action>
499 <action type="fix" issue="LANG-137">Improve javadoc and overflow behavior of Fraction.</action>
500 <action type="fix" issue="LANG-55">RandomStringUtils infloops with length &gt; 1.</action>
501 <action type="fix" issue="LANG-47">test.lang fails if compiled with non iso-8859-1 locales.</action>
502 <action type="fix" issue="LANG-113">SystemUtils does not play nice in an Applet.</action>
503 <action type="fix" issue="LANG-111">time unit tests fail on Sundays.</action>
504 <action type="fix" issue="LANG-90">java.lang.ExceptionInInitializerError thrown by JVMRandom constructor.</action>
505 <action type="fix" issue="LANG-78">StringUtils.chomp does not match Perl.</action>
506 <action type="fix" issue="LANG-36">patch and test case fixing problem with RandomStringUtils.random().</action>
507 <action type="fix" issue="LANG-151">General case: infinite loop: ToStringBuilder.reflectionToString.</action>
508 <action type="fix" issue="LANG-35">Should ToStringBuilder.reflectionToString handle arrays?.</action>
509 <action type="fix" issue="LANG-83">EnumUtils nit: The import java.io.Serializable is never used.</action>
510 <action type="fix" issue="LANG-12">Example in Javadoc for ToStringBuilder wrong for append.</action>
511 <action type="fix" issue="LANG-110">Added class hierachy support to HashCodeBuilder.reflectionHashCode().</action>
512 <action type="fix" issue="LANG-71">ExceptionUtils new methods.</action>
513 <action type="fix" issue="LANG-15">Infinite loop in StringUtils.replace(text, repl, with) + FIX.</action>
514 <action type="fix" issue="LANG-93">StackOverflow due to ToStringBuilder.</action>
515 <action type="fix" issue="LANG-39">No Javadoc for NestableDelegate.</action>
516 <action type="fix" issue="LANG-49">Specify initial size for Enum's HashMap.</action>
517 <action type="fix" issue="LANG-146">Enum does not support inner sub-classes.</action>
518 <action type="fix" issue="LANG-157">Removed compile warning in ObjectUtils.</action>
519 <action type="fix" issue="LANG-96">SystemUtils.IS_JAVA_1_5 Javadoc is wrong.</action>
520 <action type="fix" issue="LANG-16">NumberRange inaccurate for Long, etc.</action>
521 <action type="fix" issue="LANG-4">Hierarchy support in ToStringBuilder.reflectionToString().</action>
522 <action type="fix" issue="LANG-56">StringUtils.countMatches loops forever if substring empty.</action>
523 <action type="add" issue="LANG-209">javadoc fixes (remove @links to non-public identifiers).</action>
524 <action type="add" issue="LANG-210">Add javadoc examples and tests for StringUtils.</action>
525 <action type="add" issue="LANG-170">Make NumberUtils null handling consistent.</action>
526 <action type="fix" issue="LANG-145">Unused field 'startFinal' in DateIterator.</action>
527 <action type="add" issue="LANG-214">reduce object creation in ToStringBuilder.</action>
528 <action type="add" issue="LANG-228">Improved tests, javadoc for CharSetUtils, StringEscapeUtils.</action>
529 <action type="add" issue="LANG-252">NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject.</action>
530 <action type="add" issue="LANG-208">Javadoc, tests improvements for CharSet, CharSetUtils.</action>
531 <action type="add" issue="LANG-205">StringUtil enhancement.</action>
532 <action type="add" issue="LANG-164">Javadoc nit.</action>
533 <action type="add" issue="LANG-206">Additional Lang Method Suggestions.</action>
534 <action type="add" issue="LANG-178">Make NestableDelegate methods public instead of package private.</action>
535 <action type="add" issue="LANG-174">Missing @since tags.</action>
536 <action type="add" issue="LANG-245">Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder.</action>
537 <action type="fix" issue="LANG-51">Typo in documentation.</action>
538 <action type="fix" issue="LANG-1">Patch for javadocs.</action>
539 <action type="add" issue="LANG-244">Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!.</action>
540 <action type="add" issue="LANG-231">Resurrect the WordWrapUtils from commons-sandbox/utils.</action>
541 <action type="fix" issue="LANG-139">EnumTest fails on Linux Sun JDK 1.3.0.</action>
542 <action type="add" issue="LANG-234">What to do with FastDateFormat unused private constructors.</action>
543 <action type="add" issue="LANG-240">Added class hierachy support to CompareToBuilder.reflectionCompare().</action>
544 <action type="add" issue="LANG-190">Removed compile warning in FastDateFormat.</action>
545 <action type="fix" issue="LANG-97">typo in the javadoc example code.</action>
546 <action type="add" issue="LANG-249">MethodUtils: Removed unused code/unused local vars.</action>
547 <action type="add" issue="LANG-237">Hierarchy support in EqualsBuilder.reflectionEquals().</action>
548 <action type="fix" issue="LANG-91">JavaDoc Errata.</action>
549 <action type="add" issue="LANG-215">ArrayUtils.contains().</action>
550 <action type="add" issue="LANG-221">More flexibility for getRootCause in ExceptionUtils.</action>
551 </release>
552
553 <release version="1.0.1" date="2002-11-25" description="Quick bugfix to 1.0">
554 <action type="fix">NumberRange.getMaximum returns minimum.</action>
555 <action type="fix">Enum constructor validations.</action>
556 <action type="fix">NestableException/Delegate is not serializable.</action>
557 <action type="fix">split using null and max less than actual token count adds "null".</action>
558 <action type="add">ExceptionUtils cannot handle J2EE-Exception in a default way.</action>
559 </release>
560
561 <release version="1.0" date="2002-10-04" description="First release of Commons Lang">
562 </release>
563
564 </body>
565 </document>
0 #!/bin/sh
1 # Just call the standard mirrors.cgi script. It will use download.html
2 # as the input template.
3 exec /www/www.apache.org/dyn/mirrors/mirrors.cgi $*
4141
4242 DEPRECATIONS:
4343
44 Much of the exception subpackage was reworked betwen 1.0-b1 and 1.0. Apart
44 Much of the exception subpackage was reworked between 1.0-b1 and 1.0. Apart
4545 from this the API should have a high level of backward compatibility.
4646
4747
126126 16193 Hierarchy support in EqualsBuilder.reflectionEquals()
127127 16202 typo in the javadoc example code
128128 16204 Infinite loop in StringUtils.replace(text, repl, with) + FIX
129 16227 Added class hierachy support to CompareToBuilder.reflectionC
130 16228 Added class hierachy support to HashCodeBuilder.reflectionHa
129 16227 Added class hierarchy support to CompareToBuilder.reflectionC
130 16228 Added class hierarchy support to HashCodeBuilder.reflectionHa
131131 16284 MethodUtils: Removed unused code/unused local vars.
132132 16341 No Javadoc for NestableDelegate
133133 16622 Removed compile warning in FastDateFormat
110110
111111 [LANG-11] Depend on JDK 1.5+.
112112 [LANG-302] StrBuilder does not implement clone().
113 [LANG-339] StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanes, etc.
113 [LANG-339] StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese, etc.
114114 [LANG-369] ExceptionUtils not thread-safe.
115115 [LANG-418] Javadoc incorrect for StringUtils.endsWithIgnoreCase.
116116 [LANG-428] StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for ""
0 $Id: RELEASE-NOTES.txt 1555524 2014-01-05 15:24:49Z britter $
1
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16
17
18 Apache Commons Lang
19 Version 3.2.1
20 Release Notes
21
22
23 INTRODUCTION:
24
25 This document contains the release notes for the 3.2.1 version of
26 Apache Commons Lang. Commons Lang is a set of utility functions and reusable
27 components that should be of use in any Java environment. Commons Lang 3.2.1
28 at least requires Java 6.0.
29
30 For the advice on upgrading from 2.x to 3.x, see the following page:
31
32 http://commons.apache.org/lang/article3_0.html
33
34 BUG FIXES
35 ===========
36
37 o LANG-937: Fix missing Hamcrest dependency in Ant Build
38 o LANG-941: Test failure in LocaleUtilsTest when building with JDK 8
39 o LANG-942: Test failure in FastDateParserTest and FastDateFormat_ParserTest
40 when building with JDK8. Thanks to Bruno P. Kinoshita,
41 Henri Yandell.
42 o LANG-938: Build fails with test failures when building with JDK 8
43
44 Release Notes for version 3.2
45
46 COMPATIBILITY WITH 3.1
47 ========================
48
49 This release introduces backwards incompatible changes in
50 org.apache.commons.lang3.time.FastDateFormat:
51 o Method 'protected java.util.List parsePattern()' has been removed
52 o Method 'protected java.lang.String parseToken(java.lang.String, int[])' has
53 been removed
54 o Method 'protected org.apache.commons.lang3.time.FastDateFormat$NumberRule
55 selectNumberRule(int, int)' has been removed
56
57 These changes were the result of [LANG-462]. It is assumed that this change
58 will not break clients as Charles Honton pointed out on 25/Jan/12:
59 "
60 1. Methods "FastDateFormat$NumberRule selectNumberRule(int, int)" and
61 "List<Rule> parsePattern()" couldn't have been overridden because
62 NumberRule and Rule were private to FastDateFormat.
63 2. Due to the factory pattern used, it's unlikely other two methods would have
64 been overridden.
65 3. The four methods are highly implementation specific. I consider it a
66 mistake that the methods were exposed.
67 "
68 For more information see https://issues.apache.org/jira/browse/LANG-462.
69
70 NEW FEATURES
71 ==============
72
73 o LANG-934: Add removeFinalModifier to FieldUtils
74 o LANG-863: Method returns number of inheritance hops between parent and
75 subclass. Thanks to Daneel S. Yaitskov.
76 o LANG-774: Added isStarted, isSuspended and isStopped to StopWatch.
77 Thanks to Erhan Bagdemir.
78 o LANG-848: Added StringUtils.isBlank/isEmpty CharSequence... methods.
79 Thanks to Alexander Muthmann.
80 o LANG-926: Added ArrayUtils.reverse(array, from, to) methods.
81 o LANG-795: StringUtils.toString(byte[], String) deprecated in favour of a new
82 StringUtils.toString(byte[], CharSet). Thanks to Aaron Digulla.
83 o LANG-893: StrSubstitutor now supports default values for variables.
84 Thanks to Woonsan Ko.
85 o LANG-913: Adding .gitignore to commons-lang. Thanks to Allon Mureinik.
86 o LANG-837: Add ObjectUtils.toIdentityString methods that support
87 StringBuilder, StrBuilder, and Appendable.
88 o LANG-886: Added CharSetUtils.containsAny(String, String).
89 o LANG-797: Added escape/unescapeJson to StringEscapeUtils.
90 o LANG-875: Added appendIfMissing and prependIfMissing methods to StringUtils.
91 o LANG-870: Add StringUtils.LF and StringUtils.CR values.
92 o LANG-873: Add FieldUtils getAllFields() to return all the fields defined in
93 the given class and super classes.
94 o LANG-835: StrBuilder should support StringBuilder as an input parameter.
95 o LANG-857: StringIndexOutOfBoundsException in CharSequenceTranslator.
96 o LANG-856: Code refactoring in NumberUtils.
97 o LANG-855: NumberUtils#createBigInteger does not allow for hex and octal
98 numbers.
99 o LANG-854: NumberUtils#createNumber - does not allow for hex numbers to be
100 larger than Long.
101 o LANG-853: StringUtils join APIs for primitives.
102 o LANG-841: Add StringUtils API to call String.replaceAll in DOTALL a.k.a.
103 single-line mode.
104 o LANG-825: Create StrBuilder APIs similar to
105 String.format(String, Object...).
106 o LANG-675: Add Triple class (ternary version of Pair).
107 o LANG-462: FastDateFormat supports parse methods.
108
109 BUG FIXES
110 ===========
111
112 o LANG-932: Spelling fixes. Thanks to Ville Skyttä.
113 o LANG-929: OctalUnescaper tried to parse all of \279.
114 o LANG-928: OctalUnescaper had bugs when parsing octals starting with a zero.
115 o LANG-905: EqualsBuilder returned true when comparing arrays, even when the
116 elements are different.
117 o LANG-917: Fixed exception when combining custom and choice format in
118 ExtendedMessageFormat. Thanks to Arne Burmeister.
119 o LANG-902: RandomStringUtils.random javadoc was incorrectly promising letters
120 and numbers would, as opposed to may, appear Issue:. Thanks to
121 Andrzej Winnicki.
122 o LANG-921: BooleanUtils.xor(boolean...) produces wrong results.
123 o LANG-896: BooleanUtils.toBoolean(String str) javadoc is not updated. Thanks
124 to Mark Bryan Yu.
125 o LANG-879: LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese"
126 of JDK7.
127 o LANG-836: StrSubstitutor does not support StringBuilder or CharSequence.
128 Thanks to Arnaud Brunet.
129 o LANG-693: Method createNumber from NumberUtils doesn't work for floating
130 point numbers other than Float Issue: LANG-693. Thanks to
131 Calvin Echols.
132 o LANG-887: FastDateFormat does not use the locale specific cache correctly.
133 o LANG-754: ClassUtils.getShortName(String) will now only do a reverse lookup
134 for array types.
135 o LANG-881: NumberUtils.createNumber() Javadoc says it does not work for octal
136 numbers.
137 o LANG-865: LocaleUtils.toLocale does not parse strings starting with an
138 underscore.
139 o LANG-858: StringEscapeUtils.escapeJava() and escapeEcmaScript() do not
140 output the escaped surrogate pairs that are Java parsable.
141 o LANG-849: FastDateFormat and FastDatePrinter generates Date objects
142 wastefully.
143 o LANG-845: Spelling fixes.
144 o LANG-844: Fix examples contained in javadoc of StringUtils.center methods.
145 o LANG-832: FastDateParser does not handle unterminated quotes correctly.
146 o LANG-831: FastDateParser does not handle white-space properly.
147 o LANG-830: FastDateParser could use \Q \E to quote regexes.
148 o LANG-828: FastDateParser does not handle non-Gregorian calendars properly.
149 o LANG-826: FastDateParser does not handle non-ASCII digits correctly.
150 o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--".
151 o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar
152 instances passed to format().
153 o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8.
154 o LANG-813: StringUtils.equalsIgnoreCase doesn't check string reference
155 equality.
156 o LANG-810: StringUtils.join() endIndex, bugged for loop.
157 o LANG-807: RandomStringUtils throws confusing IAE when end <= start.
158 o LANG-805: RandomStringUtils.random(count, 0, 0, false, false, universe,
159 random) always throws java.lang.ArrayIndexOutOfBoundsException.
160 o LANG-802: LocaleUtils - unnecessary recursive call in SyncAvoid class.
161 o LANG-800: Javadoc bug in DateUtils#ceiling for Calendar and Object versions.
162 o LANG-788: SerializationUtils throws ClassNotFoundException when cloning
163 primitive classes.
164 o LANG-786: StringUtils equals() relies on undefined behavior.
165 o LANG-783: Documentation bug: StringUtils.split.
166 o LANG-777: jar contains velocity template of release notes.
167 o LANG-776: TypeUtilsTest contains incorrect type assignability assertion.
168 o LANG-775: TypeUtils.getTypeArguments() misses type arguments for
169 partially-assigned classes.
170 o LANG-773: ImmutablePair doc contains nonsense text.
171 o LANG-772: ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text.
172 o LANG-765: EventListenerSupport.ProxyInvocationHandler no longer defines
173 serialVersionUID.
174 o LANG-764: StrBuilder is now serializable.
175 o LANG-761: Fix Javadoc Ant warnings.
176 o LANG-747: NumberUtils does not handle Long Hex numbers.
177 o LANG-743: Javadoc bug in static inner class DateIterator.
178
179 CHANGES
180 =========
181
182 o LANG-931: Misleading Javadoc comment in StrBuilderReader class. Thanks
183 to Christoph Schneegans.
184 o LANG-910: StringUtils.normalizeSpace now handles non-breaking spaces
185 (Unicode 00A0). Thanks to Timur Yarosh.
186 o LANG-804: Redundant check for zero in HashCodeBuilder ctor. Thanks to
187 Allon Mureinik.
188 o LANG-884: Simplify FastDateFormat; eliminate boxing.
189 o LANG-882: LookupTranslator now works with implementations of CharSequence
190 other than String.
191 o LANG-846: Provide CharSequenceUtils.regionMatches with a proper green
192 implementation instead of inefficiently converting to Strings.
193 o LANG-839: ArrayUtils removeElements methods use unnecessary HashSet.
194 o LANG-838: ArrayUtils removeElements methods clone temporary index arrays
195 unnecessarily.
196 o LANG-799: DateUtils#parseDate uses default locale; add Locale support.
197 o LANG-798: Use generics in SerializationUtils.
198
199 CHANGES WITHOUT TICKET
200 ========================
201
202 o Fixed URLs in javadoc to point to new oracle.com pages
203
204
205 Release Notes for version 3.1
206
207 NEW FEATURES
208 ==============
209
210 o LANG-801: Add Conversion utility to convert between data types on byte level
211 o LANG-760: Add API StringUtils.toString(byte[] intput, String charsetName)
212 o LANG-756: Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and
213 isPrimitiveOrWrapper(Class<?>)
214 o LANG-695: SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system
215
216 BUG FIXES
217 ===========
218
219 o LANG-749: Incorrect Bundle-SymbolicName in Manifest
220 o LANG-746: NumberUtils does not handle upper-case hex: 0X and -0X
221 o LANG-744: StringUtils throws java.security.AccessControlException on Google
222 App Engine
223 o LANG-741: Ant build has wrong component.name
224 o LANG-698: Document that the Mutable numbers don't work as expected with
225 String.format
226
227 CHANGES
228 =========
229
230 o LANG-758: Add an example with whitespace in StringUtils.defaultIfEmpty
231 o LANG-752: Fix createLong() so it behaves like createInteger()
232 o LANG-751: Include the actual type in the Validate.isInstance and
233 isAssignableFrom exception messages
234 o LANG-748: Deprecating chomp(String, String)
235 o LANG-736: CharUtils static final array CHAR_STRING is not needed to compute
236 CHAR_STRING_ARRAY
237
238
239 Release Notes for version 3.0
240
241 ADDITIONS
242 ===========
243
244 o LANG-276: MutableBigDecimal and MutableBigInteger.
245 o LANG-285: Wish : method unaccent.
246 o LANG-358: ObjectUtils.coalesce.
247 o LANG-386: LeftOf/RightOfNumber in Range convenience methods necessary.
248 o LANG-435: Add ClassUtils.isAssignable() variants with autoboxing.
249 o LANG-444: StringUtils.emptyToNull.
250 o LANG-482: Enhance StrSubstitutor to support nested ${var-${subvr}} expansion
251 o LANG-482: StrSubstitutor now supports substitution in variable names.
252 o LANG-496: A generic implementation of the Lazy initialization pattern.
253 o LANG-497: Addition of ContextedException and ContextedRuntimeException.
254 o LANG-498: Add StringEscapeUtils.escapeText() methods.
255 o LANG-499: Add support for the handling of ExecutionExceptions.
256 o LANG-501: Add support for background initialization.
257 o LANG-529: Add a concurrent package.
258 o LANG-533: Validate: support for validating blank strings.
259 o LANG-537: Add ArrayUtils.toArray to create generic arrays.
260 o LANG-545: Add ability to create a Future for a constant.
261 o LANG-546: Add methods to Validate to check whether the index is valid for
262 the array/list/string.
263 o LANG-553: Add TypeUtils class to provide utility code for working with generic
264 types.
265 o LANG-559: Added isAssignableFrom and isInstanceOf validation methods.
266 o LANG-559: Added validState validation method.
267 o LANG-560: New TimedSemaphore class.
268 o LANG-582: Provide an implementation of the ThreadFactory interface.
269 o LANG-588: Create a basic Pair<L, R> class.
270 o LANG-594: DateUtils equal & compare functions up to most significant field.
271 o LANG-601: Add Builder Interface / Update Builders to Implement It.
272 o LANG-609: Support lazy initialization using atomic variables
273 o LANG-610: Extend exception handling in ConcurrentUtils to runtime exceptions.
274 o LANG-614: StringUtils.endsWithAny method
275 o LANG-640: Add normalizeSpace to StringUtils
276 o LANG-644: Provide documentation about the new concurrent package
277 o LANG-649: BooleanUtils.toBooleanObject to support single character input
278 o LANG-651: Add AnnotationUtils
279 o LANG-653: Provide a very basic ConcurrentInitializer implementation
280 o LANG-655: Add StringUtils.defaultIfBlank()
281 o LANG-667: Add a Null-safe compare() method to ObjectUtils
282 o LANG-676: Documented potential NPE if auto-boxing occurs for some BooleanUtils
283 methods
284 o LANG-678: Add support for ConcurrentMap.putIfAbsent()
285 o LANG-692: Add hashCodeMulti varargs method
286 o LANG-697: Add FormattableUtils class
287 o LANG-684: Levenshtein Distance Within a Given Threshold
288
289 REMOVALS
290 ==========
291
292 o LANG-438: Remove @deprecateds.
293 o LANG-492: Remove code handled now by the JDK.
294 o LANG-493: Remove code that does not hold enough value to remain.
295 o LANG-590: Remove JDK 1.2/1.3 bug handling in
296 StringUtils.indexOf(String, String, int).
297 o LANG-673: WordUtils.abbreviate() removed
298 o LANG-691: Removed DateUtils.UTC_TIME_ZONE
299
300 IMPROVEMENTS
301 ==============
302
303 o LANG-290: EnumUtils for JDK 5.0.
304 o LANG-336: Finally start using generics.
305 o LANG-355: StrBuilder should implement CharSequence and Appendable.
306 o LANG-396: Investigate for vararg usages.
307 o LANG-424: Improve Javadoc for StringUtils class.
308 o LANG-458: Refactor Validate.java to eliminate code redundancy.
309 o LANG-479: Document where in SVN trunk is.
310 o LANG-504: bring ArrayUtils.isEmpty to the generics world.
311 o LANG-505: Rewrite StringEscapeUtils.
312 o LANG-507: StringEscapeUtils.unescapeJava should support \u+ notation.
313 o LANG-510: Convert StringUtils API to take CharSequence.
314 o LANG-513: Better EnumUtils.
315 o LANG-528: Mutable classes should implement an appropriately typed Mutable
316 interface.
317 o LANG-539: Compile commons.lang for CDC 1.1/Foundation 1.1.
318 o LANG-540: Make NumericEntityEscaper immutable.
319 o LANG-541: Replace StringBuffer with StringBuilder.
320 o LANG-548: Use Iterable on API instead of Collection.
321 o LANG-551: Replace Range classes with generic version.
322 o LANG-562: Change Maven groupId.
323 o LANG-563: Change Java package name.
324 o LANG-570: Do the test cases really still require main() and suite() methods?
325 o LANG-579: Add new Validate methods.
326 o LANG-599: ClassUtils.getClass(): Allow Dots as Inner Class Separators.
327 o LANG-605: DefaultExceptionContext overwrites values in recursive situations.
328 o LANG-668: Change ObjectUtils min() & max() functions to use varargs rather
329 than just two parameters
330 o LANG-681: Push down WordUtils to "text" sub-package.
331 o LANG-711: Add includeantruntime=false to javac targets to quell warnings in
332 ant 1.8.1 and better (and modest performance gain).
333 o LANG-713: Increase test coverage of FieldUtils read methods and tweak
334 javadoc.
335 o LANG-718: build.xml Java 1.5+ updates.
336
337 BUG FIXES
338 ===========
339
340 o LANG-11: Depend on JDK 1.5+.
341 o LANG-302: StrBuilder does not implement clone().
342 o LANG-339: StringEscapeUtils.escapeHtml() escapes multibyte characters like
343 Chinese, Japanese, etc.
344 o LANG-369: ExceptionUtils not thread-safe.
345 o LANG-418: Javadoc incorrect for StringUtils.endsWithIgnoreCase.
346 o LANG-428: StringUtils.isAlpha, isAlphanumeric and isNumeric now return false
347 for ""
348 o LANG-439: StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20).
349 o LANG-448: Lower Ascii Characters don't get encoded by Entities.java.
350 o LANG-468: JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder).
351 o LANG-474: Fixes for thread safety.
352 o LANG-478: StopWatch does not resist to system time changes.
353 o LANG-480: StringEscapeUtils.escapeHtml incorrectly converts unicode
354 characters above U+00FFFF into 2 characters.
355 o LANG-481: Possible race-conditions in hashCode of the range classes.
356 o LANG-564: Improve StrLookup API documentation.
357 o LANG-568: @SuppressWarnings("unchecked") is used too generally.
358 o LANG-571: ArrayUtils.add(T[: array, T element) can create unexpected
359 ClassCastException.
360 o LANG-585: exception.DefaultExceptionContext.getFormattedExceptionMessage
361 catches Throwable.
362 o LANG-596: StrSubstitutor should also handle the default properties of a
363 java.util.Properties class
364 o LANG-600: Javadoc is incorrect for public static int
365 lastIndexOf(String str, String searchStr).
366 o LANG-602: ContextedRuntimeException no longer an 'unchecked' exception.
367 o LANG-606: EqualsBuilder causes StackOverflowException.
368 o LANG-608: Some StringUtils methods should take an int character instead of
369 char to use String API features.
370 o LANG-617: StringEscapeUtils.escapeXML() can't process UTF-16 supplementary
371 characters
372 o LANG-624: SystemUtils.getJavaVersionAsFloat throws
373 StringIndexOutOfBoundsException on Android runtime/Dalvik VM
374 o LANG-629: Charset may not be threadsafe, because the HashSet is not synch.
375 o LANG-638: NumberUtils createNumber throws a StringIndexOutOfBoundsException
376 when argument containing "e" and "E" is passed in
377 o LANG-643: Javadoc StringUtils.left() claims to throw on negative len, but
378 doesn't
379 o LANG-645: FastDateFormat.format() outputs incorrect week of year because
380 locale isn't respected
381 o LANG-646: StringEscapeUtils.unescapeJava doesn't handle octal escapes and
382 Unicode with extra u
383 o LANG-656: Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect
384 o LANG-658: Some Entitys like &Ouml; are not matched properly against its
385 ISO8859-1 representation
386 o LANG-659: EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212
387 ISOtech
388 o LANG-66: StringEscaper.escapeXml() escapes characters > 0x7f.
389 o LANG-662: org.apache.commons.lang3.math.Fraction does not reduce
390 (Integer.MIN_VALUE, 2^k)
391 o LANG-663: org.apache.commons.lang3.math.Fraction does not always succeed in
392 multiplyBy and divideBy
393 o LANG-664: NumberUtils.isNumber(String) is not right when the String is
394 "1.1L"
395 o LANG-672: Doc bug in DateUtils#ceiling
396 o LANG-677: DateUtils.isSameLocalTime compares using 12 hour clock and not
397 24 hour
398 o LANG-685: EqualsBuilder synchronizes on HashCodeBuilder.
399 o LANG-703: StringUtils.join throws NPE when toString returns null for one of
400 objects in collection
401 o LANG-710: StringIndexOutOfBoundsException when calling unescapeHtml4("&#03")
402 o LANG-714: StringUtils doc/comment spelling fixes.
403 o LANG-715: CharSetUtils.squeeze() speedup.
404 o LANG-716: swapCase and *capitalize speedups.
405
406
407 Historical list of changes: http://commons.apache.org/lang/changes-report.html
408
409 For complete information on Commons Lang, including instructions on how to
410 submit bug reports, patches, or suggestions for improvement, see the
411 Apache Commons Lang website:
412
413 http://commons.apache.org/lang/
414
415 Have fun!
416 -Apache Commons Lang team
417
0 $Id: RELEASE-NOTES-3.2.txt 1553851 2013-12-28 15:51:31Z britter $
1
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16
17
18 Apache Commons Lang
19 Version 3.2
20 Release Notes
21
22
23 INTRODUCTION:
24
25 This document contains the release notes for the 3.2 version of
26 Apache Commons Lang. Commons Lang is a set of utility functions and reusable
27 components that should be of use in any Java environment. Commons Lang 3.2
28 at least requires Java 6.0.
29
30 For the advice on upgrading from 2.x to 3.x, see the following page:
31
32 http://commons.apache.org/lang/article3_0.html
33
34 COMPATIBILITY WITH 3.1
35 ========================
36
37 This release introduces backwards incompatible changes in
38 org.apache.commons.lang3.time.FastDateFormat:
39 o Method 'protected java.util.List parsePattern()' has been removed
40 o Method 'protected java.lang.String parseToken(java.lang.String, int[])' has
41 been removed
42 o Method 'protected org.apache.commons.lang3.time.FastDateFormat$NumberRule
43 selectNumberRule(int, int)' has been removed
44
45 These changes were the result of [LANG-462]. It is assumed that this change
46 will not break clients as Charles Honton pointed out on 25/Jan/12:
47 "
48 1. Methods "FastDateFormat$NumberRule selectNumberRule(int, int)" and
49 "List<Rule> parsePattern()" couldn't have been overridden because
50 NumberRule and Rule were private to FastDateFormat.
51 2. Due to the factory pattern used, it's unlikely other two methods would have
52 been overridden.
53 3. The four methods are highly implementation specific. I consider it a
54 mistake that the methods were exposed.
55 "
56 For more information see https://issues.apache.org/jira/browse/LANG-462.
57
58 NEW FEATURES
59 ==============
60
61 o LANG-934: Add removeFinalModifier to FieldUtils
62 o LANG-863: Method returns number of inheritance hops between parent and
63 subclass. Thanks to Daneel S. Yaitskov.
64 o LANG-774: Added isStarted, isSuspended and isStopped to StopWatch.
65 Thanks to Erhan Bagdemir.
66 o LANG-848: Added StringUtils.isBlank/isEmpty CharSequence... methods.
67 Thanks to Alexander Muthmann.
68 o LANG-926: Added ArrayUtils.reverse(array, from, to) methods.
69 o LANG-795: StringUtils.toString(byte[], String) deprecated in favour of a new
70 StringUtils.toString(byte[], CharSet). Thanks to Aaron Digulla.
71 o LANG-893: StrSubstitutor now supports default values for variables.
72 Thanks to Woonsan Ko.
73 o LANG-913: Adding .gitignore to commons-lang. Thanks to Allon Mureinik.
74 o LANG-837: Add ObjectUtils.toIdentityString methods that support
75 StringBuilder, StrBuilder, and Appendable.
76 o LANG-886: Added CharSetUtils.containsAny(String, String).
77 o LANG-797: Added escape/unescapeJson to StringEscapeUtils.
78 o LANG-875: Added appendIfMissing and prependIfMissing methods to StringUtils.
79 o LANG-870: Add StringUtils.LF and StringUtils.CR values.
80 o LANG-873: Add FieldUtils getAllFields() to return all the fields defined in
81 the given class and super classes.
82 o LANG-835: StrBuilder should support StringBuilder as an input parameter.
83 o LANG-857: StringIndexOutOfBoundsException in CharSequenceTranslator.
84 o LANG-856: Code refactoring in NumberUtils.
85 o LANG-855: NumberUtils#createBigInteger does not allow for hex and octal
86 numbers.
87 o LANG-854: NumberUtils#createNumber - does not allow for hex numbers to be
88 larger than Long.
89 o LANG-853: StringUtils join APIs for primitives.
90 o LANG-841: Add StringUtils API to call String.replaceAll in DOTALL a.k.a.
91 single-line mode.
92 o LANG-825: Create StrBuilder APIs similar to
93 String.format(String, Object...).
94 o LANG-675: Add Triple class (ternary version of Pair).
95 o LANG-462: FastDateFormat supports parse methods.
96
97 BUG FIXES
98 ===========
99
100 o LANG-932: Spelling fixes. Thanks to Ville Skyttä.
101 o LANG-929: OctalUnescaper tried to parse all of \279.
102 o LANG-928: OctalUnescaper had bugs when parsing octals starting with a zero.
103 o LANG-905: EqualsBuilder returned true when comparing arrays, even when the
104 elements are different.
105 o LANG-917: Fixed exception when combining custom and choice format in
106 ExtendedMessageFormat. Thanks to Arne Burmeister.
107 o LANG-902: RandomStringUtils.random javadoc was incorrectly promising letters
108 and numbers would, as opposed to may, appear Issue:. Thanks to
109 Andrzej Winnicki.
110 o LANG-921: BooleanUtils.xor(boolean...) produces wrong results.
111 o LANG-896: BooleanUtils.toBoolean(String str) javadoc is not updated. Thanks
112 to Mark Bryan Yu.
113 o LANG-879: LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese"
114 of JDK7.
115 o LANG-836: StrSubstitutor does not support StringBuilder or CharSequence.
116 Thanks to Arnaud Brunet.
117 o LANG-693: Method createNumber from NumberUtils doesn't work for floating
118 point numbers other than Float Issue: LANG-693. Thanks to
119 Calvin Echols.
120 o LANG-887: FastDateFormat does not use the locale specific cache correctly.
121 o LANG-754: ClassUtils.getShortName(String) will now only do a reverse lookup
122 for array types.
123 o LANG-881: NumberUtils.createNumber() Javadoc says it does not work for octal
124 numbers.
125 o LANG-865: LocaleUtils.toLocale does not parse strings starting with an
126 underscore.
127 o LANG-858: StringEscapeUtils.escapeJava() and escapeEcmaScript() do not
128 output the escaped surrogate pairs that are Java parsable.
129 o LANG-849: FastDateFormat and FastDatePrinter generates Date objects
130 wastefully.
131 o LANG-845: Spelling fixes.
132 o LANG-844: Fix examples contained in javadoc of StringUtils.center methods.
133 o LANG-832: FastDateParser does not handle unterminated quotes correctly.
134 o LANG-831: FastDateParser does not handle white-space properly.
135 o LANG-830: FastDateParser could use \Q \E to quote regexes.
136 o LANG-828: FastDateParser does not handle non-Gregorian calendars properly.
137 o LANG-826: FastDateParser does not handle non-ASCII digits correctly.
138 o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--".
139 o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar
140 instances passed to format().
141 o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8.
142 o LANG-813: StringUtils.equalsIgnoreCase doesn't check string reference
143 equality.
144 o LANG-810: StringUtils.join() endIndex, bugged for loop.
145 o LANG-807: RandomStringUtils throws confusing IAE when end <= start.
146 o LANG-805: RandomStringUtils.random(count, 0, 0, false, false, universe,
147 random) always throws java.lang.ArrayIndexOutOfBoundsException.
148 o LANG-802: LocaleUtils - unnecessary recursive call in SyncAvoid class.
149 o LANG-800: Javadoc bug in DateUtils#ceiling for Calendar and Object versions.
150 o LANG-788: SerializationUtils throws ClassNotFoundException when cloning
151 primitive classes.
152 o LANG-786: StringUtils equals() relies on undefined behavior.
153 o LANG-783: Documentation bug: StringUtils.split.
154 o LANG-777: jar contains velocity template of release notes.
155 o LANG-776: TypeUtilsTest contains incorrect type assignability assertion.
156 o LANG-775: TypeUtils.getTypeArguments() misses type arguments for
157 partially-assigned classes.
158 o LANG-773: ImmutablePair doc contains nonsense text.
159 o LANG-772: ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text.
160 o LANG-765: EventListenerSupport.ProxyInvocationHandler no longer defines
161 serialVersionUID.
162 o LANG-764: StrBuilder is now serializable.
163 o LANG-761: Fix Javadoc Ant warnings.
164 o LANG-747: NumberUtils does not handle Long Hex numbers.
165 o LANG-743: Javadoc bug in static inner class DateIterator.
166
167 CHANGES
168 =========
169
170 o LANG-931: Misleading Javadoc comment in StrBuilderReader class. Thanks
171 to Christoph Schneegans.
172 o LANG-910: StringUtils.normalizeSpace now handles non-breaking spaces
173 (Unicode 00A0). Thanks to Timur Yarosh.
174 o LANG-804: Redundant check for zero in HashCodeBuilder ctor. Thanks to
175 Allon Mureinik.
176 o LANG-884: Simplify FastDateFormat; eliminate boxing.
177 o LANG-882: LookupTranslator now works with implementations of CharSequence
178 other than String.
179 o LANG-846: Provide CharSequenceUtils.regionMatches with a proper green
180 implementation instead of inefficiently converting to Strings.
181 o LANG-839: ArrayUtils removeElements methods use unnecessary HashSet.
182 o LANG-838: ArrayUtils removeElements methods clone temporary index arrays
183 unnecessarily.
184 o LANG-799: DateUtils#parseDate uses default locale; add Locale support.
185 o LANG-798: Use generics in SerializationUtils.
186
187 CHANGES WITHOUT TICKET
188 ========================
189
190 o Fixed URLs in javadoc to point to new oracle.com pages
191
192
193 Release Notes for version 3.1
194
195 NEW FEATURES
196 ==============
197
198 o LANG-801: Add Conversion utility to convert between data types on byte level
199 o LANG-760: Add API StringUtils.toString(byte[] intput, String charsetName)
200 o LANG-756: Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and
201 isPrimitiveOrWrapper(Class<?>)
202 o LANG-695: SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system
203
204 BUG FIXES
205 ===========
206
207 o LANG-749: Incorrect Bundle-SymbolicName in Manifest
208 o LANG-746: NumberUtils does not handle upper-case hex: 0X and -0X
209 o LANG-744: StringUtils throws java.security.AccessControlException on Google
210 App Engine
211 o LANG-741: Ant build has wrong component.name
212 o LANG-698: Document that the Mutable numbers don't work as expected with
213 String.format
214
215 CHANGES
216 =========
217
218 o LANG-758: Add an example with whitespace in StringUtils.defaultIfEmpty
219 o LANG-752: Fix createLong() so it behaves like createInteger()
220 o LANG-751: Include the actual type in the Validate.isInstance and
221 isAssignableFrom exception messages
222 o LANG-748: Deprecating chomp(String, String)
223 o LANG-736: CharUtils static final array CHAR_STRING is not needed to compute
224 CHAR_STRING_ARRAY
225
226
227 Release Notes for version 3.0
228
229 ADDITIONS
230 ===========
231
232 o LANG-276: MutableBigDecimal and MutableBigInteger.
233 o LANG-285: Wish : method unaccent.
234 o LANG-358: ObjectUtils.coalesce.
235 o LANG-386: LeftOf/RightOfNumber in Range convenience methods necessary.
236 o LANG-435: Add ClassUtils.isAssignable() variants with autoboxing.
237 o LANG-444: StringUtils.emptyToNull.
238 o LANG-482: Enhance StrSubstitutor to support nested ${var-${subvr}} expansion
239 o LANG-482: StrSubstitutor now supports substitution in variable names.
240 o LANG-496: A generic implementation of the Lazy initialization pattern.
241 o LANG-497: Addition of ContextedException and ContextedRuntimeException.
242 o LANG-498: Add StringEscapeUtils.escapeText() methods.
243 o LANG-499: Add support for the handling of ExecutionExceptions.
244 o LANG-501: Add support for background initialization.
245 o LANG-529: Add a concurrent package.
246 o LANG-533: Validate: support for validating blank strings.
247 o LANG-537: Add ArrayUtils.toArray to create generic arrays.
248 o LANG-545: Add ability to create a Future for a constant.
249 o LANG-546: Add methods to Validate to check whether the index is valid for
250 the array/list/string.
251 o LANG-553: Add TypeUtils class to provide utility code for working with generic
252 types.
253 o LANG-559: Added isAssignableFrom and isInstanceOf validation methods.
254 o LANG-559: Added validState validation method.
255 o LANG-560: New TimedSemaphore class.
256 o LANG-582: Provide an implementation of the ThreadFactory interface.
257 o LANG-588: Create a basic Pair<L, R> class.
258 o LANG-594: DateUtils equal & compare functions up to most significant field.
259 o LANG-601: Add Builder Interface / Update Builders to Implement It.
260 o LANG-609: Support lazy initialization using atomic variables
261 o LANG-610: Extend exception handling in ConcurrentUtils to runtime exceptions.
262 o LANG-614: StringUtils.endsWithAny method
263 o LANG-640: Add normalizeSpace to StringUtils
264 o LANG-644: Provide documentation about the new concurrent package
265 o LANG-649: BooleanUtils.toBooleanObject to support single character input
266 o LANG-651: Add AnnotationUtils
267 o LANG-653: Provide a very basic ConcurrentInitializer implementation
268 o LANG-655: Add StringUtils.defaultIfBlank()
269 o LANG-667: Add a Null-safe compare() method to ObjectUtils
270 o LANG-676: Documented potential NPE if auto-boxing occurs for some BooleanUtils
271 methods
272 o LANG-678: Add support for ConcurrentMap.putIfAbsent()
273 o LANG-692: Add hashCodeMulti varargs method
274 o LANG-697: Add FormattableUtils class
275 o LANG-684: Levenshtein Distance Within a Given Threshold
276
277 REMOVALS
278 ==========
279
280 o LANG-438: Remove @deprecateds.
281 o LANG-492: Remove code handled now by the JDK.
282 o LANG-493: Remove code that does not hold enough value to remain.
283 o LANG-590: Remove JDK 1.2/1.3 bug handling in
284 StringUtils.indexOf(String, String, int).
285 o LANG-673: WordUtils.abbreviate() removed
286 o LANG-691: Removed DateUtils.UTC_TIME_ZONE
287
288 IMPROVEMENTS
289 ==============
290
291 o LANG-290: EnumUtils for JDK 5.0.
292 o LANG-336: Finally start using generics.
293 o LANG-355: StrBuilder should implement CharSequence and Appendable.
294 o LANG-396: Investigate for vararg usages.
295 o LANG-424: Improve Javadoc for StringUtils class.
296 o LANG-458: Refactor Validate.java to eliminate code redundancy.
297 o LANG-479: Document where in SVN trunk is.
298 o LANG-504: bring ArrayUtils.isEmpty to the generics world.
299 o LANG-505: Rewrite StringEscapeUtils.
300 o LANG-507: StringEscapeUtils.unescapeJava should support \u+ notation.
301 o LANG-510: Convert StringUtils API to take CharSequence.
302 o LANG-513: Better EnumUtils.
303 o LANG-528: Mutable classes should implement an appropriately typed Mutable
304 interface.
305 o LANG-539: Compile commons.lang for CDC 1.1/Foundation 1.1.
306 o LANG-540: Make NumericEntityEscaper immutable.
307 o LANG-541: Replace StringBuffer with StringBuilder.
308 o LANG-548: Use Iterable on API instead of Collection.
309 o LANG-551: Replace Range classes with generic version.
310 o LANG-562: Change Maven groupId.
311 o LANG-563: Change Java package name.
312 o LANG-570: Do the test cases really still require main() and suite() methods?
313 o LANG-579: Add new Validate methods.
314 o LANG-599: ClassUtils.getClass(): Allow Dots as Inner Class Separators.
315 o LANG-605: DefaultExceptionContext overwrites values in recursive situations.
316 o LANG-668: Change ObjectUtils min() & max() functions to use varargs rather
317 than just two parameters
318 o LANG-681: Push down WordUtils to "text" sub-package.
319 o LANG-711: Add includeantruntime=false to javac targets to quell warnings in
320 ant 1.8.1 and better (and modest performance gain).
321 o LANG-713: Increase test coverage of FieldUtils read methods and tweak
322 javadoc.
323 o LANG-718: build.xml Java 1.5+ updates.
324
325 BUG FIXES
326 ===========
327
328 o LANG-11: Depend on JDK 1.5+.
329 o LANG-302: StrBuilder does not implement clone().
330 o LANG-339: StringEscapeUtils.escapeHtml() escapes multibyte characters like
331 Chinese, Japanese, etc.
332 o LANG-369: ExceptionUtils not thread-safe.
333 o LANG-418: Javadoc incorrect for StringUtils.endsWithIgnoreCase.
334 o LANG-428: StringUtils.isAlpha, isAlphanumeric and isNumeric now return false
335 for ""
336 o LANG-439: StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20).
337 o LANG-448: Lower Ascii Characters don't get encoded by Entities.java.
338 o LANG-468: JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder).
339 o LANG-474: Fixes for thread safety.
340 o LANG-478: StopWatch does not resist to system time changes.
341 o LANG-480: StringEscapeUtils.escapeHtml incorrectly converts unicode
342 characters above U+00FFFF into 2 characters.
343 o LANG-481: Possible race-conditions in hashCode of the range classes.
344 o LANG-564: Improve StrLookup API documentation.
345 o LANG-568: @SuppressWarnings("unchecked") is used too generally.
346 o LANG-571: ArrayUtils.add(T[: array, T element) can create unexpected
347 ClassCastException.
348 o LANG-585: exception.DefaultExceptionContext.getFormattedExceptionMessage
349 catches Throwable.
350 o LANG-596: StrSubstitutor should also handle the default properties of a
351 java.util.Properties class
352 o LANG-600: Javadoc is incorrect for public static int
353 lastIndexOf(String str, String searchStr).
354 o LANG-602: ContextedRuntimeException no longer an 'unchecked' exception.
355 o LANG-606: EqualsBuilder causes StackOverflowException.
356 o LANG-608: Some StringUtils methods should take an int character instead of
357 char to use String API features.
358 o LANG-617: StringEscapeUtils.escapeXML() can't process UTF-16 supplementary
359 characters
360 o LANG-624: SystemUtils.getJavaVersionAsFloat throws
361 StringIndexOutOfBoundsException on Android runtime/Dalvik VM
362 o LANG-629: Charset may not be threadsafe, because the HashSet is not synch.
363 o LANG-638: NumberUtils createNumber throws a StringIndexOutOfBoundsException
364 when argument containing "e" and "E" is passed in
365 o LANG-643: Javadoc StringUtils.left() claims to throw on negative len, but
366 doesn't
367 o LANG-645: FastDateFormat.format() outputs incorrect week of year because
368 locale isn't respected
369 o LANG-646: StringEscapeUtils.unescapeJava doesn't handle octal escapes and
370 Unicode with extra u
371 o LANG-656: Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect
372 o LANG-658: Some Entitys like &Ouml; are not matched properly against its
373 ISO8859-1 representation
374 o LANG-659: EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212
375 ISOtech
376 o LANG-66: StringEscaper.escapeXml() escapes characters > 0x7f.
377 o LANG-662: org.apache.commons.lang3.math.Fraction does not reduce
378 (Integer.MIN_VALUE, 2^k)
379 o LANG-663: org.apache.commons.lang3.math.Fraction does not always succeed in
380 multiplyBy and divideBy
381 o LANG-664: NumberUtils.isNumber(String) is not right when the String is
382 "1.1L"
383 o LANG-672: Doc bug in DateUtils#ceiling
384 o LANG-677: DateUtils.isSameLocalTime compares using 12 hour clock and not
385 24 hour
386 o LANG-685: EqualsBuilder synchronizes on HashCodeBuilder.
387 o LANG-703: StringUtils.join throws NPE when toString returns null for one of
388 objects in collection
389 o LANG-710: StringIndexOutOfBoundsException when calling unescapeHtml4("&#03")
390 o LANG-714: StringUtils doc/comment spelling fixes.
391 o LANG-715: CharSetUtils.squeeze() speedup.
392 o LANG-716: swapCase and *capitalize speedups.
393
394
395 Historical list of changes: http://commons.apache.org/lang/changes-report.html
396
397 For complete information on Commons Lang, including instructions on how to
398 submit bug reports, patches, or suggestions for improvement, see the
399 Apache Commons Lang website:
400
401 http://commons.apache.org/lang/
402
403 Have fun!
404 -Apache Commons Lang team
405
2727 <item name="Download" href="/download_lang.cgi"/>
2828 <item name="Users guide" href="/userguide.html"/>
2929 <item name="Release History" href="/release-history.html"/>
30 <item name="Javadoc (3.0.1 release)" href="api-release/index.html"/>
30 <item name="Javadoc (Latest release)" href="javadocs/api-release/index.html"/>
3131 </menu>
3232
3333 <menu name="Development">
184184 <li>StringUtils.isAlpha, isNumeric and isAlphanumeric now all return false when passed an empty String. Previously they returned true. </li>
185185 <li>SystemUtils.isJavaVersionAtLeast now relies on the <code>java.specification.version</code> and not the <code>java.version</code> System property. </li>
186186 <li>StringEscapeUtils.escapeXml and escapeHtml no longer escape high value Unicode characters by default. The text.translate package is available to recreate the old behaviour. </li>
187 <li>Validate utility methods have been changed and genericized to return the
188 validated argument where possible, to allow for inline use. </li>
189 <li>Validate utility methods handle validity violations arising from
190 <code>null</code> values by throwing <code>NullPointerException</code>s.
191 This better aligns with standard JDK behavior (lang <em>is</em> intended to
192 complement <code>java.lang</code>, after all). Users upgrading from v2.x may
193 need to adjust to this change. See <code>Validate#isTrue()</code> for a
194 general-purpose mechanism to raise an <code>IllegalArgumentException</code>.</li>
187195 </ul>
188196 </section>
189197
1919 </properties>
2020 <body>
2121
22 <!-- $Id: developerguide.xml 930469 2010-04-03 04:37:26Z bayard $ -->
22 <!-- $Id: developerguide.xml 1401523 2012-10-24 00:50:52Z ggregory $ -->
2323
2424 <section name='Developer guide for Commons "Lang"'>
2525
140140 <h3>5.BUILDING</h3>
141141 <h4>Building a Release</h4>
142142 <p>
143 The currently targetted version of Java is 1.5.
143 The currently targeted version of Java is 1.5.
144144 </p>
145145 <p>
146146 To build Lang:
4444 -->
4545 <document>
4646 <properties>
47 <title>Download Commons Lang</title>
47 <title>Download Apache Commons Lang</title>
4848 <author email="dev@commons.apache.org">Commons Documentation Team</author>
4949 </properties>
5050 <body>
51 <section name="Download Commons Lang">
51 <section name="Download Apache Commons Lang">
5252 <subsection name="Using a Mirror">
5353 <p>
5454 We recommend you use a mirror to download our release
5555 builds, but you <strong>must</strong> verify the integrity of
56 the downloaded files using signatures downloaded from our main
56 the downloaded files using signatures downloaded from our main
5757 distribution directories. Recent releases (48 hours) may not yet
5858 be available from the mirrors.
5959 </p>
7070
7171 <form action="[location]" method="get" id="SelectMirror">
7272 <p>
73 Other mirrors:
73 Other mirrors:
7474 <select name="Preferred">
7575 [if-any http]
7676 [for http]<option value="[http]">[http]</option>[end]
8989 <p>
9090 The <a href="http://www.apache.org/dist/commons/KEYS">KEYS</a>
9191 link links to the code signing keys used to sign the product.
92 The <code>PGP</code> link downloads the OpenPGP compatible signature from our main site.
92 The <code>PGP</code> link downloads the OpenPGP compatible signature from our main site.
9393 The <code>MD5</code> link downloads the checksum from the main site.
9494 </p>
9595 </subsection>
9696 </section>
97 <section name="Commons Lang 3.1 (Java 5.0+)">
97 <section name="Apache Commons Lang 3.2.1 (Java 6.0+)">
9898 <subsection name="Binaries">
9999 <table>
100100 <tr>
101 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.1-bin.tar.gz">commons-lang3-3.1-bin.tar.gz</a></td>
102 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.1-bin.tar.gz.md5">md5</a></td>
103 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.1-bin.tar.gz.asc">pgp</a></td>
101 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.2.1-bin.tar.gz">commons-lang3-3.2.1-bin.tar.gz</a></td>
102 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.2.1-bin.tar.gz.md5">md5</a></td>
103 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.2.1-bin.tar.gz.asc">pgp</a></td>
104104 </tr>
105105 <tr>
106 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.1-bin.zip">commons-lang3-3.1-bin.zip</a></td>
107 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.1-bin.zip.md5">md5</a></td>
108 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.1-bin.zip.asc">pgp</a></td>
106 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.2.1-bin.zip">commons-lang3-3.2.1-bin.zip</a></td>
107 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.2.1-bin.zip.md5">md5</a></td>
108 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.2.1-bin.zip.asc">pgp</a></td>
109109 </tr>
110110 </table>
111111 </subsection>
112112 <subsection name="Source">
113113 <table>
114114 <tr>
115 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.1-src.tar.gz">commons-lang3-3.1-src.tar.gz</a></td>
116 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.1-src.tar.gz.md5">md5</a></td>
117 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.1-src.tar.gz.asc">pgp</a></td>
115 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.2.1-src.tar.gz">commons-lang3-3.2.1-src.tar.gz</a></td>
116 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.2.1-src.tar.gz.md5">md5</a></td>
117 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.2.1-src.tar.gz.asc">pgp</a></td>
118118 </tr>
119119 <tr>
120 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.1-src.zip">commons-lang3-3.1-src.zip</a></td>
121 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.1-src.zip.md5">md5</a></td>
122 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.1-src.zip.asc">pgp</a></td>
120 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.2.1-src.zip">commons-lang3-3.2.1-src.zip</a></td>
121 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.2.1-src.zip.md5">md5</a></td>
122 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang3-3.2.1-src.zip.asc">pgp</a></td>
123 </tr>
124 </table>
125 </subsection>
126 </section>
127 <section name="Apache Commons Lang 2.6 (Requires Java 1.2 or later)">
128 <subsection name="Binaries">
129 <table>
130 <tr>
131 <td><a href="[preferred]/commons/lang/binaries/commons-lang-2.6-bin.tar.gz">commons-lang-2.6-bin.tar.gz</a></td>
132 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang-2.6-bin.tar.gz.md5">md5</a></td>
133 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang-2.6-bin.tar.gz.asc">pgp</a></td>
134 </tr>
135 <tr>
136 <td><a href="[preferred]/commons/lang/binaries/commons-lang-2.6-bin.zip">commons-lang-2.6-bin.zip</a></td>
137 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang-2.6-bin.zip.md5">md5</a></td>
138 <td><a href="http://www.apache.org/dist/commons/lang/binaries/commons-lang-2.6-bin.zip.asc">pgp</a></td>
139 </tr>
140 </table>
141 </subsection>
142 <subsection name="Source">
143 <table>
144 <tr>
145 <td><a href="[preferred]/commons/lang/source/commons-lang-2.6-src.tar.gz">commons-lang-2.6-src.tar.gz</a></td>
146 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang-2.6-src.tar.gz.md5">md5</a></td>
147 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang-2.6-src.tar.gz.asc">pgp</a></td>
148 </tr>
149 <tr>
150 <td><a href="[preferred]/commons/lang/source/commons-lang-2.6-src.zip">commons-lang-2.6-src.zip</a></td>
151 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang-2.6-src.zip.md5">md5</a></td>
152 <td><a href="http://www.apache.org/dist/commons/lang/source/commons-lang-2.6-src.zip.asc">pgp</a></td>
123153 </tr>
124154 </table>
125155 </subsection>
4949 The JavaDoc API documents are available online:
5050 </p>
5151 <ul>
52 <li>The <a href="api-3.1/index.html">current stable release 3.1</a> [Java 5.0+]</li>
53 <li>The <a href="api-2.6/index.html">legacy release 2.6</a> [Java 1.2+]</li>
52 <li>The <a href="javadocs/api-3.2.1/index.html">current stable release 3.2.1</a> [Java 6.0+]</li>
53 <li>The <a href="javadocs/api-2.6/index.html">legacy release 2.6</a> [Java 1.2+]</li>
5454 <li>Older releases - see the <a href="release-history.html">Release History</a> page</li>
5555 </ul>
5656 <p>
5757 The <a href="source-repository.html">subversion repository</a> can be
58 <a href="http://svn.apache.org/viewvc/commons/proper/lang/trunk/">browsed</a>.
58 <a href="http://svn.apache.org/viewvc/commons/proper/lang/trunk/">browsed</a>, or you can browse/contribute via <a href="https://github.com/apache/commons-lang">GitHub</a>.
59 </p>
60 <p>
61 The code base is monitored by a Sonar instance running on <a href="https://analysis.apache.org/dashboard/index/72046">analysis.apache.org</a>.
5962 </p>
6063 </section>
6164 <!-- ================================================== -->
6265 <section name="Release Information">
63 <p>The latest stable release of Lang is 3.1. You may: </p>
66 <p>The latest stable release of Lang is 3.2.1. You may: </p>
6467 <ul>
65 <li>Download <a href="http://commons.apache.org/lang/download_lang.cgi">3.1</a></li>
66 <li>Read the <a href="release-notes/RELEASE-NOTES-3.1.txt">3.1 release notes</a></li>
68 <li>Download <a href="http://commons.apache.org/lang/download_lang.cgi">3.2.1</a></li>
69 <li>Read the <a href="release-notes/RELEASE-NOTES-3.2.1.txt">3.2.1 release notes</a></li>
6770 <li>Examine the <a href="article3_0.html">2.x to 3.0 upgrade notes</a></li>
6871 <li>Compare major versions via the <a href="lang2-lang3-clirr-report.html">Lang2 to Lang3 Clirr report</a></li>
6972 </ul>
73
74 <p>The <a href="clirr-report.html">Clirr report</a> for release 3.2.1 shows three errors in <code>org.apache.commons.lang3.time.FastDateFormat</code>. These were introduced in release 3.2 and are assumed not to affect client code. For more information please see the
75 <a href="release-notes/RELEASE-NOTES-3.2.1.txt">release notes</a>.</p>
7076
7177 <p>
7278 Alternatively you can pull it from the central Maven repositories:
7379 <pre>
7480 &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
7581 &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;
76 &lt;version&gt;3.1&lt;/version&gt;
82 &lt;version&gt;3.2.1&lt;/version&gt;
7783 </pre>
7884 </p>
7985
8086 <p>
8187 For information on previous releases see the <a href="release-history.html">Release History</a>, and to download previous releases see the <a href="http://archive.apache.org/dist/commons/lang/">Commons Lang Archive</a>.
8288 </p>
89 </section>
90 <!-- ================================================== -->
91 <section name="Getting Involved">
92 <p>
93 The <a href="mail-lists.html">commons developer mailing list</a> is the main channel of communication for contributors. Please remember that the lists are shared between all commons components, so prefix your email by [lang]. </p>
94 <p>You can also visit the #apache-commons IRC channel on irc.freenode.net or peruse <a href="issue-tracking.html">JIRA</a>. Specific links of interest for JIRA are:</p>
95 <ul>
96 <li>Ideas looking for code: <a href="https://issues.apache.org/jira/issues/?jql=project%20%3D%20LANG%20AND%20resolution%20%3D%20Unresolved%20AND%20fixVersion%20%3D%20%22Patch%20Needed%22%20ORDER%20BY%20priority%20DESC">Patch Needed</a></li>
97 <li>Issues with patches, looking for reviews: <a href="https://issues.apache.org/jira/issues/?jql=fixVersion%20%3D%20%22Review%20Patch%22%20AND%20project%20%3D%20LANG%20AND%20resolution%20%3D%20Unresolved%20ORDER%20BY%20priority%20DESC">Review Patch</a></li>
98 </ul>
99 <p>If you'd like to offer up pull requests via GitHub rather than applying patches to JIRA, we have a <a href="https://github.com/apache/commons-lang/">GitHub mirror</a>. </p>
83100 </section>
84101 <!-- ================================================== -->
85102 <section name="Support">
148148 <td>
149149 <strong>Commons Commits List</strong>
150150 <br /><br />
151 Only for e-mails automatically generated by the <a href="source-repository.html">source control</a> sytem.
151 Only for e-mails automatically generated by the <a href="source-repository.html">source control</a> system.
152152 <br /><br />
153153 </td>
154154 <td><a href="mailto:commits-subscribe@commons.apache.org">Subscribe</a></td>
2727
2828 <table>
2929 <tr><th>Version</th><th>Release date</th><th>Javadoc</th><th>Release notes</th></tr>
30 <tr><td>3.0.1.1</td><td>9/Aug/11</td><td><a href="api-3.0.1/">api-3.0.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.0.1.txt">release notes for 3.0.1</a></td></tr>
31 <tr><td>3.0</td><td>18/Jul/11</td><td><a href="api-3.0/">api-3.0</a></td><td><a href="release-notes/RELEASE-NOTES-3.0.txt">release notes for 3.0</a></td></tr>
32 <tr><td>2.6</td><td>16/Jan/11</td><td><a href="api-2.6/">api-2.6</a></td><td><a href="release-notes/RELEASE-NOTES-2.6.txt">release notes for 2.6</a></td></tr>
33 <tr><td>2.5</td><td>23/Feb/10</td><td><a href="api-2.5/">api-2.5</a></td><td><a href="release-notes/RELEASE-NOTES-2.5.txt">release notes for 2.5</a></td></tr>
34 <tr><td>2.4</td><td>18/Mar/08</td><td><a href="api-2.4/">api-2.4</a></td><td><a href="release-notes/RELEASE-NOTES-2.4.txt">release notes for 2.4</a></td></tr>
35 <tr><td>2.3</td><td>13/Feb/07</td><td><a href="api-2.3/">api-2.3</a></td><td><a href="release-notes/RELEASE-NOTES-2.3.txt">release notes for 2.3</a></td></tr>
36 <tr><td>2.2</td><td>04/Oct/06</td><td><a href="api-2.2/">api-2.2</a></td><td><a href="release-notes/RELEASE-NOTES-2.2.txt">release notes for 2.2</a></td></tr>
37 <tr><td>2.1</td><td>13/Jun/06</td><td><a href="api-2.1/">api-2.1</a></td><td><a href="release-notes/RELEASE-NOTES-2.1.txt">release notes for 2.1</a></td></tr>
38 <tr><td>2.0</td><td>02/Sep/03</td><td><a href="api-2.0/">api-2.0</a></td><td><a href="release-notes/RELEASE-NOTES-2.0.txt">release notes for 2.0</a></td></tr>
39 <tr><td>1.0.1</td><td>25/Nov/02</td><td><a href="api-1.0.1/">api-1.0.1</a></td><td><a href="release-notes/RELEASE-NOTES-1.0.1.txt">release notes for 1.0.1</a></td></tr>
40 <tr><td>1.0</td><td>04/Oct/02</td><td><a href="api-1.0/">api-1.0</a></td><td><a href="release-notes/RELEASE-NOTES-1.0.txt">release notes for 1.0</a></td></tr>
30 <tr><td>3.2.1</td><td>05/Jan/14</td><td><a href="javadocs/api-3.2.1/">api-3.2.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.2.1.txt">release notes for 3.2.1</a></td></tr>
31 <tr><td>3.2</td><td>01/Jan/14</td><td><a href="javadocs/api-3.2/">api-3.2</a></td><td><a href="release-notes/RELEASE-NOTES-3.2.txt">release notes for 3.2</a></td></tr>
32 <tr><td>3.1</td><td>14/Nov/11</td><td><a href="javadocs/api-3.1/">api-3.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.1.txt">release notes for 3.1</a></td></tr>
33 <tr><td>3.0.1</td><td>9/Aug/11</td><td><a href="javadocs/api-3.0.1/">api-3.0.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.0.1.txt">release notes for 3.0.1</a></td></tr>
34 <tr><td>3.0</td><td>18/Jul/11</td><td><a href="javadocs/api-3.0/">api-3.0</a></td><td><a href="release-notes/RELEASE-NOTES-3.0.txt">release notes for 3.0</a></td></tr>
35 <tr><td>2.6</td><td>16/Jan/11</td><td><a href="javadocs/api-2.6/">api-2.6</a></td><td><a href="release-notes/RELEASE-NOTES-2.6.txt">release notes for 2.6</a></td></tr>
36 <tr><td>2.5</td><td>23/Feb/10</td><td><a href="javadocs/api-2.5/">api-2.5</a></td><td><a href="release-notes/RELEASE-NOTES-2.5.txt">release notes for 2.5</a></td></tr>
37 <tr><td>2.4</td><td>18/Mar/08</td><td><a href="javadocs/api-2.4/">api-2.4</a></td><td><a href="release-notes/RELEASE-NOTES-2.4.txt">release notes for 2.4</a></td></tr>
38 <tr><td>2.3</td><td>13/Feb/07</td><td><a href="javadocs/api-2.3/">api-2.3</a></td><td><a href="release-notes/RELEASE-NOTES-2.3.txt">release notes for 2.3</a></td></tr>
39 <tr><td>2.2</td><td>04/Oct/06</td><td><a href="javadocs/api-2.2/">api-2.2</a></td><td><a href="release-notes/RELEASE-NOTES-2.2.txt">release notes for 2.2</a></td></tr>
40 <tr><td>2.1</td><td>13/Jun/06</td><td><a href="javadocs/api-2.1/">api-2.1</a></td><td><a href="release-notes/RELEASE-NOTES-2.1.txt">release notes for 2.1</a></td></tr>
41 <tr><td>2.0</td><td>02/Sep/03</td><td><a href="javadocs/api-2.0/">api-2.0</a></td><td><a href="release-notes/RELEASE-NOTES-2.0.txt">release notes for 2.0</a></td></tr>
42 <tr><td>1.0.1</td><td>25/Nov/02</td><td><a href="javadocs/api-1.0.1/">api-1.0.1</a></td><td><a href="release-notes/RELEASE-NOTES-1.0.1.txt">release notes for 1.0.1</a></td></tr>
43 <tr><td>1.0</td><td>04/Oct/02</td><td><a href="javadocs/api-1.0/">api-1.0</a></td><td><a href="release-notes/RELEASE-NOTES-1.0.txt">release notes for 1.0</a></td></tr>
4144 </table>
4245
4346 </section>
148148 16193 Hierarchy support in EqualsBuilder.reflectionEquals()
149149 16202 typo in the javadoc example code
150150 16204 Infinite loop in StringUtils.replace(text, repl, with) + FIX
151 16227 Added class hierachy support to CompareToBuilder.reflectionC
152 16228 Added class hierachy support to HashCodeBuilder.reflectionHa
151 16227 Added class hierarchy support to CompareToBuilder.reflectionC
152 16228 Added class hierarchy support to HashCodeBuilder.reflectionHa
153153 16284 MethodUtils: Removed unused code/unused local vars.
154154 16341 No Javadoc for NestableDelegate
155155 16622 Removed compile warning in FastDateFormat
123123
124124 [LANG-11] Depend on JDK 1.5+.
125125 [LANG-302] StrBuilder does not implement clone().
126 [LANG-339] StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanes, etc.
126 [LANG-339] StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese, etc.
127127 [LANG-369] ExceptionUtils not thread-safe.
128128 [LANG-418] Javadoc incorrect for StringUtils.endsWithIgnoreCase.
129129 [LANG-428] StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for ""
2323 </properties>
2424
2525 <body>
26 <!-- $Id: userguide.xml 1148224 2011-07-19 08:28:56Z bayard $ -->
26 <!-- $Id: userguide.xml 1401523 2012-10-24 00:50:52Z ggregory $ -->
2727
2828 <section name='User guide for Commons "Lang"'>
2929 <div align="center">
293293 high load, if multiple threads access the initializer concurrently, it is
294294 possible that the <code>initialize()</code> method is invoked multiple
295295 times. The class guarantees that <code>get()</code> always returns the
296 same object though; so objects created accidently are immideately discarded.
296 same object though; so objects created accidentally are immideately discarded.
297297 </p>
298298 <p>
299299 With <code>AtomicSafeInitializer</code> there is yet another variant
535535 need on demand. However, sometimes it is desired to set some properties of
536536 the newly created worker threads. This is possible through the
537537 <code>ThreadFactory</code> interface; an implementation of this interface
538 has to be created and pased to an executor on creation time. Currently, the
538 has to be created and passed to an executor on creation time. Currently, the
539539 JDK does not provide an implementation of <code>ThreadFactory</code>, so
540540 one has to start from scratch.
541541 </p>
4040 import org.junit.Test;
4141
4242 /**
43 * @version $Id: AnnotationUtilsTest.java 1132388 2011-06-05 12:44:13Z sebb $
43 * @version $Id: AnnotationUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
4444 */
4545 public class AnnotationUtilsTest {
4646 @TestAnnotation(
429429
430430 @Test
431431 public void testIsValidAnnotationMemberType() {
432 for (Class<?> type : new Class[] { byte.class, short.class, int.class, char.class,
432 for (final Class<?> type : new Class[] { byte.class, short.class, int.class, char.class,
433433 long.class, float.class, double.class, boolean.class, String.class, Class.class,
434434 NestAnnotation.class, TestAnnotation.class, Stooge.class, ElementType.class }) {
435435 assertTrue(AnnotationUtils.isValidAnnotationMemberType(type));
436436 assertTrue(AnnotationUtils.isValidAnnotationMemberType(Array.newInstance(type, 0)
437437 .getClass()));
438438 }
439 for (Class<?> type : new Class[] { Object.class, Map.class, Collection.class }) {
439 for (final Class<?> type : new Class[] { Object.class, Map.class, Collection.class }) {
440440 assertFalse(AnnotationUtils.isValidAnnotationMemberType(type));
441441 assertFalse(AnnotationUtils.isValidAnnotationMemberType(Array.newInstance(type, 0)
442442 .getClass()));
448448 final Test real = getClass().getDeclaredMethod(
449449 "testGeneratedAnnotationEquivalentToRealAnnotation").getAnnotation(Test.class);
450450
451 InvocationHandler generatedTestInvocationHandler = new InvocationHandler() {
452
453 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
451 final InvocationHandler generatedTestInvocationHandler = new InvocationHandler() {
452
453 @Override
454 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
454455 if ("equals".equals(method.getName()) && method.getParameterTypes().length == 1) {
455456 return Boolean.valueOf(proxy == args[0]);
456457 }
464465 }
465466 };
466467
467 Test generated = (Test) Proxy.newProxyInstance(Thread.currentThread()
468 final Test generated = (Test) Proxy.newProxyInstance(Thread.currentThread()
468469 .getContextClassLoader(), new Class[] { Test.class },
469470 generatedTestInvocationHandler);
470471 assertTrue(real.equals(generated));
472473 assertTrue(AnnotationUtils.equals(generated, real));
473474 assertTrue(AnnotationUtils.equals(real, generated));
474475
475 Test generated2 = (Test) Proxy.newProxyInstance(Thread.currentThread()
476 final Test generated2 = (Test) Proxy.newProxyInstance(Thread.currentThread()
476477 .getContextClassLoader(), new Class[] { Test.class },
477478 generatedTestInvocationHandler);
478479 assertFalse(generated.equals(generated2));
495496 public void testToString() throws Exception {
496497 final Test testAnno = getClass().getDeclaredMethod("testToString")
497498 .getAnnotation(Test.class);
498 String toString = AnnotationUtils.toString(testAnno);
499 final String toString = AnnotationUtils.toString(testAnno);
499500 assertTrue(toString.startsWith("@org.junit.Test("));
500501 assertTrue(toString.endsWith(")"));
501502 assertTrue(toString.contains("expected=class org.junit.Test$None"));
3030 /**
3131 * Tests ArrayUtils add methods.
3232 *
33 * @version $Id: ArrayUtilsAddTest.java 1199894 2011-11-09 17:53:59Z ggregory $
33 * @version $Id: ArrayUtilsAddTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3434 */
3535 public class ArrayUtilsAddTest {
3636
4545 // Invalid - can't store Long in Integer array
4646 n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
4747 fail("Should have generated IllegalArgumentException");
48 } catch (IllegalArgumentException expected) {
48 } catch (final IllegalArgumentException expected) {
4949 }
5050 }
5151
5858 newArray = ArrayUtils.add((boolean[])null, true);
5959 assertTrue(Arrays.equals(new boolean[]{true}, newArray));
6060 assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
61 boolean[] array1 = new boolean[]{true, false, true};
61 final boolean[] array1 = new boolean[]{true, false, true};
6262 newArray = ArrayUtils.add(array1, false);
6363 assertTrue(Arrays.equals(new boolean[]{true, false, true, false}, newArray));
6464 assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
7373 newArray = ArrayUtils.add((byte[])null, (byte)1);
7474 assertTrue(Arrays.equals(new byte[]{1}, newArray));
7575 assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
76 byte[] array1 = new byte[]{1, 2, 3};
76 final byte[] array1 = new byte[]{1, 2, 3};
7777 newArray = ArrayUtils.add(array1, (byte)0);
7878 assertTrue(Arrays.equals(new byte[]{1, 2, 3, 0}, newArray));
7979 assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
9191 newArray = ArrayUtils.add((char[])null, (char)1);
9292 assertTrue(Arrays.equals(new char[]{1}, newArray));
9393 assertEquals(Character.TYPE, newArray.getClass().getComponentType());
94 char[] array1 = new char[]{1, 2, 3};
94 final char[] array1 = new char[]{1, 2, 3};
9595 newArray = ArrayUtils.add(array1, (char)0);
9696 assertTrue(Arrays.equals(new char[]{1, 2, 3, 0}, newArray));
9797 assertEquals(Character.TYPE, newArray.getClass().getComponentType());
109109 newArray = ArrayUtils.add((double[])null, 1);
110110 assertTrue(Arrays.equals(new double[]{1}, newArray));
111111 assertEquals(Double.TYPE, newArray.getClass().getComponentType());
112 double[] array1 = new double[]{1, 2, 3};
112 final double[] array1 = new double[]{1, 2, 3};
113113 newArray = ArrayUtils.add(array1, 0);
114114 assertTrue(Arrays.equals(new double[]{1, 2, 3, 0}, newArray));
115115 assertEquals(Double.TYPE, newArray.getClass().getComponentType());
127127 newArray = ArrayUtils.add((float[])null, 1);
128128 assertTrue(Arrays.equals(new float[]{1}, newArray));
129129 assertEquals(Float.TYPE, newArray.getClass().getComponentType());
130 float[] array1 = new float[]{1, 2, 3};
130 final float[] array1 = new float[]{1, 2, 3};
131131 newArray = ArrayUtils.add(array1, 0);
132132 assertTrue(Arrays.equals(new float[]{1, 2, 3, 0}, newArray));
133133 assertEquals(Float.TYPE, newArray.getClass().getComponentType());
145145 newArray = ArrayUtils.add((int[])null, 1);
146146 assertTrue(Arrays.equals(new int[]{1}, newArray));
147147 assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
148 int[] array1 = new int[]{1, 2, 3};
148 final int[] array1 = new int[]{1, 2, 3};
149149 newArray = ArrayUtils.add(array1, 0);
150150 assertTrue(Arrays.equals(new int[]{1, 2, 3, 0}, newArray));
151151 assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
163163 newArray = ArrayUtils.add((long[])null, 1);
164164 assertTrue(Arrays.equals(new long[]{1}, newArray));
165165 assertEquals(Long.TYPE, newArray.getClass().getComponentType());
166 long[] array1 = new long[]{1, 2, 3};
166 final long[] array1 = new long[]{1, 2, 3};
167167 newArray = ArrayUtils.add(array1, 0);
168168 assertTrue(Arrays.equals(new long[]{1, 2, 3, 0}, newArray));
169169 assertEquals(Long.TYPE, newArray.getClass().getComponentType());
181181 newArray = ArrayUtils.add((short[])null, (short)1);
182182 assertTrue(Arrays.equals(new short[]{1}, newArray));
183183 assertEquals(Short.TYPE, newArray.getClass().getComponentType());
184 short[] array1 = new short[]{1, 2, 3};
184 final short[] array1 = new short[]{1, 2, 3};
185185 newArray = ArrayUtils.add(array1, (short)0);
186186 assertTrue(Arrays.equals(new short[]{1, 2, 3, 0}, newArray));
187187 assertEquals(Short.TYPE, newArray.getClass().getComponentType());
201201 assertEquals(String.class, newArray.getClass().getComponentType());
202202
203203 //show that not casting to Object[] is okay and will assume String based on "a"
204 String[] newStringArray = ArrayUtils.add(null, "a");
204 final String[] newStringArray = ArrayUtils.add(null, "a");
205205 assertTrue(Arrays.equals(new String[]{"a"}, newStringArray));
206206 assertTrue(Arrays.equals(new Object[]{"a"}, newStringArray));
207207 assertEquals(String.class, newStringArray.getClass().getComponentType());
208208
209 String[] stringArray1 = new String[]{"a", "b", "c"};
209 final String[] stringArray1 = new String[]{"a", "b", "c"};
210210 newArray = ArrayUtils.add(stringArray1, null);
211211 assertTrue(Arrays.equals(new String[]{"a", "b", "c", null}, newArray));
212212 assertEquals(String.class, newArray.getClass().getComponentType());
228228
229229 @Test
230230 public void testLANG571(){
231 String[] stringArray=null;
232 String aString=null;
231 final String[] stringArray=null;
232 final String aString=null;
233233 try {
234234 @SuppressWarnings("unused")
235 final
235236 String[] sa = ArrayUtils.add(stringArray, aString);
236237 fail("Should have caused IllegalArgumentException");
237 } catch (IllegalArgumentException iae){
238 } catch (final IllegalArgumentException iae){
238239 //expected
239240 }
240241 try {
241242 @SuppressWarnings("unused")
243 final
242244 String[] sa = ArrayUtils.add(stringArray, 0, aString);
243245 fail("Should have caused IllegalArgumentException");
244 } catch (IllegalArgumentException iae){
246 } catch (final IllegalArgumentException iae){
245247 //expected
246248 }
247249 }
250252 public void testAddObjectArrayToObjectArray() {
251253 assertNull(ArrayUtils.addAll((Object[]) null, (Object[]) null));
252254 Object[] newArray;
253 String[] stringArray1 = new String[]{"a", "b", "c"};
254 String[] stringArray2 = new String[]{"1", "2", "3"};
255 final String[] stringArray1 = new String[]{"a", "b", "c"};
256 final String[] stringArray2 = new String[]{"1", "2", "3"};
255257 newArray = ArrayUtils.addAll(stringArray1, (String[]) null);
256258 assertNotSame(stringArray1, newArray);
257259 assertTrue(Arrays.equals(stringArray1, newArray));
277279 assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray));
278280 assertTrue(Arrays.equals(new String[]{}, newArray));
279281 assertEquals(String.class, newArray.getClass().getComponentType());
280 String[] stringArrayNull = new String []{null};
282 final String[] stringArrayNull = new String []{null};
281283 newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull);
282284 assertTrue(Arrays.equals(new String[]{null, null}, newArray));
283285 assertEquals(String.class, newArray.getClass().getComponentType());
371373 assertTrue(Arrays.equals(new String[]{"a"}, newArray));
372374 assertTrue(Arrays.equals(new Object[]{"a"}, newArray));
373375 assertEquals(String.class, newArray.getClass().getComponentType());
374 String[] stringArray1 = new String[]{"a", "b", "c"};
376 final String[] stringArray1 = new String[]{"a", "b", "c"};
375377 newArray = ArrayUtils.add(stringArray1, 0, null);
376378 assertTrue(Arrays.equals(new String[]{null, "a", "b", "c"}, newArray));
377379 assertEquals(String.class, newArray.getClass().getComponentType());
386388 assertEquals(String.class, newArray.getClass().getComponentType());
387389 assertEquals(String.class, newArray.getClass().getComponentType());
388390
389 Object[] o = new Object[] {"1", "2", "4"};
390 Object[] result = ArrayUtils.add(o, 2, "3");
391 Object[] result2 = ArrayUtils.add(o, 3, "5");
391 final Object[] o = new Object[] {"1", "2", "4"};
392 final Object[] result = ArrayUtils.add(o, 2, "3");
393 final Object[] result2 = ArrayUtils.add(o, 3, "5");
392394
393395 assertNotNull(result);
394396 assertEquals(4, result.length);
408410 assertTrue( Arrays.equals( new boolean[] { true }, booleanArray ) );
409411 try {
410412 booleanArray = ArrayUtils.add( null, -1, true );
411 } catch(IndexOutOfBoundsException e) {
413 } catch(final IndexOutOfBoundsException e) {
412414 assertEquals("Index: -1, Length: 0", e.getMessage());
413415 }
414416 booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false);
419421 assertTrue( Arrays.equals( new boolean[] { true, true, false }, booleanArray ) );
420422 try {
421423 booleanArray = ArrayUtils.add( new boolean[] { true, false }, 4, true);
422 } catch(IndexOutOfBoundsException e) {
424 } catch(final IndexOutOfBoundsException e) {
423425 assertEquals("Index: 4, Length: 2", e.getMessage());
424426 }
425427 try {
426428 booleanArray = ArrayUtils.add( new boolean[] { true, false }, -1, true);
427 } catch(IndexOutOfBoundsException e) {
429 } catch(final IndexOutOfBoundsException e) {
428430 assertEquals("Index: -1, Length: 2", e.getMessage());
429431 }
430432
433435 assertTrue( Arrays.equals( new char[] { 'a' }, charArray ) );
434436 try {
435437 charArray = ArrayUtils.add( (char[]) null, -1, 'a' );
436 } catch(IndexOutOfBoundsException e) {
438 } catch(final IndexOutOfBoundsException e) {
437439 assertEquals("Index: -1, Length: 0", e.getMessage());
438440 }
439441 charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b');
446448 assertTrue( Arrays.equals( new char[] { 'a', 't', 'b', 'c' }, charArray ) );
447449 try {
448450 charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c');
449 } catch(IndexOutOfBoundsException e) {
451 } catch(final IndexOutOfBoundsException e) {
450452 assertEquals("Index: 4, Length: 2", e.getMessage());
451453 }
452454 try {
453455 charArray = ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c');
454 } catch(IndexOutOfBoundsException e) {
456 } catch(final IndexOutOfBoundsException e) {
455457 assertEquals("Index: -1, Length: 2", e.getMessage());
456458 }
457459
460462 assertTrue( Arrays.equals( new short[] { 2, 1 }, shortArray ) );
461463 try {
462464 shortArray = ArrayUtils.add( (short[]) null, -1, (short) 2);
463 } catch(IndexOutOfBoundsException e) {
465 } catch(final IndexOutOfBoundsException e) {
464466 assertEquals("Index: -1, Length: 0", e.getMessage());
465467 }
466468 shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10);
471473 assertTrue( Arrays.equals( new short[] { 2, 6, 1, 3 }, shortArray ) );
472474 try {
473475 shortArray = ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10);
474 } catch(IndexOutOfBoundsException e) {
476 } catch(final IndexOutOfBoundsException e) {
475477 assertEquals("Index: 4, Length: 2", e.getMessage());
476478 }
477479 try {
478480 shortArray = ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10);
479 } catch(IndexOutOfBoundsException e) {
481 } catch(final IndexOutOfBoundsException e) {
480482 assertEquals("Index: -1, Length: 2", e.getMessage());
481483 }
482484
485487 assertTrue( Arrays.equals( new byte[] { 2, 1 }, byteArray ) );
486488 try {
487489 byteArray = ArrayUtils.add( (byte[]) null, -1, (byte) 2);
488 } catch(IndexOutOfBoundsException e) {
490 } catch(final IndexOutOfBoundsException e) {
489491 assertEquals("Index: -1, Length: 0", e.getMessage());
490492 }
491493 byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3);
496498 assertTrue( Arrays.equals( new byte[] { 2, 6, 1, 3 }, byteArray ) );
497499 try {
498500 byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3);
499 } catch(IndexOutOfBoundsException e) {
501 } catch(final IndexOutOfBoundsException e) {
500502 assertEquals("Index: 4, Length: 2", e.getMessage());
501503 }
502504 try {
503505 byteArray = ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3);
504 } catch(IndexOutOfBoundsException e) {
506 } catch(final IndexOutOfBoundsException e) {
505507 assertEquals("Index: -1, Length: 2", e.getMessage());
506508 }
507509
510512 assertTrue( Arrays.equals( new int[] { 2, 1 }, intArray ) );
511513 try {
512514 intArray = ArrayUtils.add( (int[]) null, -1, 2);
513 } catch(IndexOutOfBoundsException e) {
515 } catch(final IndexOutOfBoundsException e) {
514516 assertEquals("Index: -1, Length: 0", e.getMessage());
515517 }
516518 intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10);
521523 assertTrue( Arrays.equals( new int[] { 2, 6, 1, 3 }, intArray ) );
522524 try {
523525 intArray = ArrayUtils.add( new int[] { 2, 6 }, 4, 10);
524 } catch(IndexOutOfBoundsException e) {
526 } catch(final IndexOutOfBoundsException e) {
525527 assertEquals("Index: 4, Length: 2", e.getMessage());
526528 }
527529 try {
528530 intArray = ArrayUtils.add( new int[] { 2, 6 }, -1, 10);
529 } catch(IndexOutOfBoundsException e) {
531 } catch(final IndexOutOfBoundsException e) {
530532 assertEquals("Index: -1, Length: 2", e.getMessage());
531533 }
532534
535537 assertTrue( Arrays.equals( new long[] { 2L, 1L }, longArray ) );
536538 try {
537539 longArray = ArrayUtils.add( (long[]) null, -1, 2L);
538 } catch(IndexOutOfBoundsException e) {
540 } catch(final IndexOutOfBoundsException e) {
539541 assertEquals("Index: -1, Length: 0", e.getMessage());
540542 }
541543 longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L);
546548 assertTrue( Arrays.equals( new long[] { 2L, 6L, 1L, 3L }, longArray ) );
547549 try {
548550 longArray = ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L);
549 } catch(IndexOutOfBoundsException e) {
551 } catch(final IndexOutOfBoundsException e) {
550552 assertEquals("Index: 4, Length: 2", e.getMessage());
551553 }
552554 try {
553555 longArray = ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L);
554 } catch(IndexOutOfBoundsException e) {
556 } catch(final IndexOutOfBoundsException e) {
555557 assertEquals("Index: -1, Length: 2", e.getMessage());
556558 }
557559
560562 assertTrue( Arrays.equals( new float[] { 2.2f, 1.1f }, floatArray ) );
561563 try {
562564 floatArray = ArrayUtils.add( (float[]) null, -1, 2.2f);
563 } catch(IndexOutOfBoundsException e) {
565 } catch(final IndexOutOfBoundsException e) {
564566 assertEquals("Index: -1, Length: 0", e.getMessage());
565567 }
566568 floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f);
571573 assertTrue( Arrays.equals( new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray ) );
572574 try {
573575 floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f);
574 } catch(IndexOutOfBoundsException e) {
576 } catch(final IndexOutOfBoundsException e) {
575577 assertEquals("Index: 4, Length: 2", e.getMessage());
576578 }
577579 try {
578580 floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f);
579 } catch(IndexOutOfBoundsException e) {
581 } catch(final IndexOutOfBoundsException e) {
580582 assertEquals("Index: -1, Length: 2", e.getMessage());
581583 }
582584
585587 assertTrue( Arrays.equals( new double[] { 2.2, 1.1 }, doubleArray ) );
586588 try {
587589 doubleArray = ArrayUtils.add( (double[]) null, -1, 2.2);
588 } catch(IndexOutOfBoundsException e) {
590 } catch(final IndexOutOfBoundsException e) {
589591 assertEquals("Index: -1, Length: 0", e.getMessage());
590592 }
591593 doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5);
596598 assertTrue( Arrays.equals( new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray ) );
597599 try {
598600 doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5);
599 } catch(IndexOutOfBoundsException e) {
601 } catch(final IndexOutOfBoundsException e) {
600602 assertEquals("Index: 4, Length: 2", e.getMessage());
601603 }
602604 try {
603605 doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5);
604 } catch(IndexOutOfBoundsException e) {
606 } catch(final IndexOutOfBoundsException e) {
605607 assertEquals("Index: -1, Length: 2", e.getMessage());
606608 }
607609 }
1616
1717 package org.apache.commons.lang3;
1818
19 import static org.junit.Assert.*;
19 import static org.junit.Assert.assertArrayEquals;
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertNotSame;
22 import static org.junit.Assert.assertNull;
23 import static org.junit.Assert.assertTrue;
2024
2125 import java.util.Arrays;
2226
2529 /**
2630 * Tests ArrayUtils remove and removeElement methods.
2731 *
28 * @version $Id: ArrayUtilsRemoveMultipleTest.java 1147507 2011-07-17 00:30:04Z mbenson $
32 * @version $Id: ArrayUtilsRemoveMultipleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2933 */
3034 public class ArrayUtilsRemoveMultipleTest {
3135
6973
7074 @Test
7175 public void testRemoveAllObjectArrayRemoveNone() {
72 Object[] array1 = new Object[] { "foo", "bar", "baz" };
73 Object[] array2 = ArrayUtils.removeAll(array1);
76 final Object[] array1 = new Object[] { "foo", "bar", "baz" };
77 final Object[] array2 = ArrayUtils.removeAll(array1);
7478 assertNotSame(array1, array2);
7579 assertArrayEquals(array1, array2);
7680 assertEquals(Object.class, array2.getClass().getComponentType());
9397
9498 @Test
9599 public void testRemoveAllNumberArray() {
96 Number[] inarray = { Integer.valueOf(1), Long.valueOf(2L), Byte.valueOf((byte) 3) };
100 final Number[] inarray = { Integer.valueOf(1), Long.valueOf(2L), Byte.valueOf((byte) 3) };
97101 assertEquals(3, inarray.length);
98102 Number[] outarray;
99103 outarray = ArrayUtils.removeAll(inarray, 1);
167171
168172 @Test
169173 public void testRemoveAllBooleanArrayRemoveNone() {
170 boolean[] array1 = new boolean[] { true, false };
171 boolean[] array2 = ArrayUtils.removeAll(array1);
174 final boolean[] array1 = new boolean[] { true, false };
175 final boolean[] array2 = ArrayUtils.removeAll(array1);
172176 assertNotSame(array1, array2);
173177 assertTrue(Arrays.equals(array1, array2));
174178 assertEquals(boolean.class, array2.getClass().getComponentType());
233237
234238 @Test
235239 public void testRemoveAllByteArrayRemoveNone() {
236 byte[] array1 = new byte[] { 1, 2 };
237 byte[] array2 = ArrayUtils.removeAll(array1);
240 final byte[] array1 = new byte[] { 1, 2 };
241 final byte[] array2 = ArrayUtils.removeAll(array1);
238242 assertNotSame(array1, array2);
239243 assertArrayEquals(array1, array2);
240244 assertEquals(byte.class, array2.getClass().getComponentType());
299303
300304 @Test
301305 public void testRemoveAllCharArrayRemoveNone() {
302 char[] array1 = new char[] { 'a', 'b' };
303 char[] array2 = ArrayUtils.removeAll(array1);
306 final char[] array1 = new char[] { 'a', 'b' };
307 final char[] array2 = ArrayUtils.removeAll(array1);
304308 assertNotSame(array1, array2);
305309 assertArrayEquals(array1, array2);
306310 assertEquals(char.class, array2.getClass().getComponentType());
365369
366370 @Test
367371 public void testRemoveAllDoubleArrayRemoveNone() {
368 double[] array1 = new double[] { 1, 2 };
369 double[] array2 = ArrayUtils.removeAll(array1);
372 final double[] array1 = new double[] { 1, 2 };
373 final double[] array2 = ArrayUtils.removeAll(array1);
370374 assertNotSame(array1, array2);
371375 assertTrue(Arrays.equals(array1, array2));
372376 assertEquals(double.class, array2.getClass().getComponentType());
431435
432436 @Test
433437 public void testRemoveAllFloatArrayRemoveNone() {
434 float[] array1 = new float[] { 1, 2 };
435 float[] array2 = ArrayUtils.removeAll(array1);
438 final float[] array1 = new float[] { 1, 2 };
439 final float[] array2 = ArrayUtils.removeAll(array1);
436440 assertNotSame(array1, array2);
437441 assertTrue(Arrays.equals(array1, array2));
438442 assertEquals(float.class, array2.getClass().getComponentType());
456460 @Test
457461 public void testRemoveAllIntArray() {
458462 int[] array;
463 array = ArrayUtils.removeAll(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.EMPTY_INT_ARRAY);
464 assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
465 array = ArrayUtils.removeAll(new int[] { 1 }, ArrayUtils.EMPTY_INT_ARRAY);
466 assertTrue(Arrays.equals(new int[] { 1 }, array));
459467 array = ArrayUtils.removeAll(new int[] { 1 }, 0);
460468 assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array));
461469 assertEquals(Integer.TYPE, array.getClass().getComponentType());
497505
498506 @Test
499507 public void testRemoveAllIntArrayRemoveNone() {
500 int[] array1 = new int[] { 1, 2 };
501 int[] array2 = ArrayUtils.removeAll(array1);
508 final int[] array1 = new int[] { 1, 2 };
509 final int[] array2 = ArrayUtils.removeAll(array1);
502510 assertNotSame(array1, array2);
503511 assertArrayEquals(array1, array2);
504512 assertEquals(int.class, array2.getClass().getComponentType());
563571
564572 @Test
565573 public void testRemoveAllLongArrayRemoveNone() {
566 long[] array1 = new long[] { 1, 2 };
567 long[] array2 = ArrayUtils.removeAll(array1);
574 final long[] array1 = new long[] { 1, 2 };
575 final long[] array2 = ArrayUtils.removeAll(array1);
568576 assertNotSame(array1, array2);
569577 assertArrayEquals(array1, array2);
570578 assertEquals(long.class, array2.getClass().getComponentType());
629637
630638 @Test
631639 public void testRemoveAllShortArrayRemoveNone() {
632 short[] array1 = new short[] { 1, 2 };
633 short[] array2 = ArrayUtils.removeAll(array1);
640 final short[] array1 = new short[] { 1, 2 };
641 final short[] array2 = ArrayUtils.removeAll(array1);
634642 assertNotSame(array1, array2);
635643 assertArrayEquals(array1, array2);
636644 assertEquals(short.class, array2.getClass().getComponentType());
2828 /**
2929 * Tests ArrayUtils remove and removeElement methods.
3030 *
31 * @version $Id: ArrayUtilsRemoveTest.java 1158284 2011-08-16 14:11:31Z ggregory $
31 * @version $Id: ArrayUtilsRemoveTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3232 */
3333 public class ArrayUtilsRemoveTest {
3434
5050 try {
5151 ArrayUtils.remove(new Object[] {"a", "b"}, -1);
5252 fail("IndexOutOfBoundsException expected");
53 } catch (IndexOutOfBoundsException e) {}
53 } catch (final IndexOutOfBoundsException e) {}
5454 try {
5555 ArrayUtils.remove(new Object[] {"a", "b"}, 2);
5656 fail("IndexOutOfBoundsException expected");
57 } catch (IndexOutOfBoundsException e) {}
57 } catch (final IndexOutOfBoundsException e) {}
5858 try {
5959 ArrayUtils.remove((Object[]) null, 0);
6060 fail("IndexOutOfBoundsException expected");
61 } catch (IndexOutOfBoundsException e) {}
61 } catch (final IndexOutOfBoundsException e) {}
6262 }
6363
6464 @Test
6565 public void testRemoveNumberArray(){
66 Number[] inarray = {Integer.valueOf(1),Long.valueOf(2),Byte.valueOf((byte) 3)};
66 final Number[] inarray = {Integer.valueOf(1),Long.valueOf(2),Byte.valueOf((byte) 3)};
6767 assertEquals(3, inarray.length);
6868 Number[] outarray;
6969 outarray = ArrayUtils.remove(inarray, 1);
9595 try {
9696 ArrayUtils.remove(new boolean[] {true, false}, -1);
9797 fail("IndexOutOfBoundsException expected");
98 } catch (IndexOutOfBoundsException e) {}
98 } catch (final IndexOutOfBoundsException e) {}
9999 try {
100100 ArrayUtils.remove(new boolean[] {true, false}, 2);
101101 fail("IndexOutOfBoundsException expected");
102 } catch (IndexOutOfBoundsException e) {}
102 } catch (final IndexOutOfBoundsException e) {}
103103 try {
104104 ArrayUtils.remove((boolean[]) null, 0);
105105 fail("IndexOutOfBoundsException expected");
106 } catch (IndexOutOfBoundsException e) {}
106 } catch (final IndexOutOfBoundsException e) {}
107107 }
108108
109109 @Test
124124 try {
125125 ArrayUtils.remove(new byte[] {1, 2}, -1);
126126 fail("IndexOutOfBoundsException expected");
127 } catch (IndexOutOfBoundsException e) {}
127 } catch (final IndexOutOfBoundsException e) {}
128128 try {
129129 ArrayUtils.remove(new byte[] {1, 2}, 2);
130130 fail("IndexOutOfBoundsException expected");
131 } catch (IndexOutOfBoundsException e) {}
131 } catch (final IndexOutOfBoundsException e) {}
132132 try {
133133 ArrayUtils.remove((byte[]) null, 0);
134134 fail("IndexOutOfBoundsException expected");
135 } catch (IndexOutOfBoundsException e) {}
135 } catch (final IndexOutOfBoundsException e) {}
136136 }
137137
138138 @Test
153153 try {
154154 ArrayUtils.remove(new char[] {'a', 'b'}, -1);
155155 fail("IndexOutOfBoundsException expected");
156 } catch (IndexOutOfBoundsException e) {}
156 } catch (final IndexOutOfBoundsException e) {}
157157 try {
158158 ArrayUtils.remove(new char[] {'a', 'b'}, 2);
159159 fail("IndexOutOfBoundsException expected");
160 } catch (IndexOutOfBoundsException e) {}
160 } catch (final IndexOutOfBoundsException e) {}
161161 try {
162162 ArrayUtils.remove((char[]) null, 0);
163163 fail("IndexOutOfBoundsException expected");
164 } catch (IndexOutOfBoundsException e) {}
164 } catch (final IndexOutOfBoundsException e) {}
165165 }
166166
167167 @Test
182182 try {
183183 ArrayUtils.remove(new double[] {1, 2}, -1);
184184 fail("IndexOutOfBoundsException expected");
185 } catch (IndexOutOfBoundsException e) {}
185 } catch (final IndexOutOfBoundsException e) {}
186186 try {
187187 ArrayUtils.remove(new double[] {1, 2}, 2);
188188 fail("IndexOutOfBoundsException expected");
189 } catch (IndexOutOfBoundsException e) {}
189 } catch (final IndexOutOfBoundsException e) {}
190190 try {
191191 ArrayUtils.remove((double[]) null, 0);
192192 fail("IndexOutOfBoundsException expected");
193 } catch (IndexOutOfBoundsException e) {}
193 } catch (final IndexOutOfBoundsException e) {}
194194 }
195195
196196 @Test
211211 try {
212212 ArrayUtils.remove(new float[] {1, 2}, -1);
213213 fail("IndexOutOfBoundsException expected");
214 } catch (IndexOutOfBoundsException e) {}
214 } catch (final IndexOutOfBoundsException e) {}
215215 try {
216216 ArrayUtils.remove(new float[] {1, 2}, 2);
217217 fail("IndexOutOfBoundsException expected");
218 } catch (IndexOutOfBoundsException e) {}
218 } catch (final IndexOutOfBoundsException e) {}
219219 try {
220220 ArrayUtils.remove((float[]) null, 0);
221221 fail("IndexOutOfBoundsException expected");
222 } catch (IndexOutOfBoundsException e) {}
222 } catch (final IndexOutOfBoundsException e) {}
223223 }
224224
225225 @Test
240240 try {
241241 ArrayUtils.remove(new int[] {1, 2}, -1);
242242 fail("IndexOutOfBoundsException expected");
243 } catch (IndexOutOfBoundsException e) {}
243 } catch (final IndexOutOfBoundsException e) {}
244244 try {
245245 ArrayUtils.remove(new int[] {1, 2}, 2);
246246 fail("IndexOutOfBoundsException expected");
247 } catch (IndexOutOfBoundsException e) {}
247 } catch (final IndexOutOfBoundsException e) {}
248248 try {
249249 ArrayUtils.remove((int[]) null, 0);
250250 fail("IndexOutOfBoundsException expected");
251 } catch (IndexOutOfBoundsException e) {}
251 } catch (final IndexOutOfBoundsException e) {}
252252 }
253253
254254 @Test
269269 try {
270270 ArrayUtils.remove(new long[] {1, 2}, -1);
271271 fail("IndexOutOfBoundsException expected");
272 } catch (IndexOutOfBoundsException e) {}
272 } catch (final IndexOutOfBoundsException e) {}
273273 try {
274274 ArrayUtils.remove(new long[] {1, 2}, 2);
275275 fail("IndexOutOfBoundsException expected");
276 } catch (IndexOutOfBoundsException e) {}
276 } catch (final IndexOutOfBoundsException e) {}
277277 try {
278278 ArrayUtils.remove((long[]) null, 0);
279279 fail("IndexOutOfBoundsException expected");
280 } catch (IndexOutOfBoundsException e) {}
280 } catch (final IndexOutOfBoundsException e) {}
281281 }
282282
283283 @Test
298298 try {
299299 ArrayUtils.remove(new short[] {1, 2}, -1);
300300 fail("IndexOutOfBoundsException expected");
301 } catch (IndexOutOfBoundsException e) {}
301 } catch (final IndexOutOfBoundsException e) {}
302302 try {
303303 ArrayUtils.remove(new short[] {1, 2}, 2);
304304 fail("IndexOutOfBoundsException expected");
305 } catch (IndexOutOfBoundsException e) {}
305 } catch (final IndexOutOfBoundsException e) {}
306306 try {
307307 ArrayUtils.remove((short[]) null, 0);
308308 fail("IndexOutOfBoundsException expected");
309 } catch (IndexOutOfBoundsException e) {}
309 } catch (final IndexOutOfBoundsException e) {}
310310 }
311311
312312 @Test
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.assertArrayEquals;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertNotNull;
22 import static org.junit.Assert.assertNotSame;
23 import static org.junit.Assert.assertNull;
24 import static org.junit.Assert.assertSame;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
1828 import java.lang.reflect.Constructor;
1929 import java.lang.reflect.Modifier;
2030 import java.util.Arrays;
2131 import java.util.Date;
2232 import java.util.Map;
2333
24 import junit.framework.TestCase;
34 import org.junit.Test;
2535
2636 /**
2737 * Unit tests {@link org.apache.commons.lang3.ArrayUtils}.
2838 *
29 * @version $Id: ArrayUtilsTest.java 1153490 2011-08-03 13:53:35Z ggregory $
39 * @version $Id: ArrayUtilsTest.java 1535078 2013-10-23 17:23:07Z ggregory $
3040 */
31 public class ArrayUtilsTest extends TestCase {
32
33 public ArrayUtilsTest(String name) {
34 super(name);
35 }
41 @SuppressWarnings("deprecation") // deliberate use of deprecated code
42 public class ArrayUtilsTest {
3643
3744 //-----------------------------------------------------------------------
45 @Test
3846 public void testConstructor() {
3947 assertNotNull(new ArrayUtils());
40 Constructor<?>[] cons = ArrayUtils.class.getDeclaredConstructors();
48 final Constructor<?>[] cons = ArrayUtils.class.getDeclaredConstructors();
4149 assertEquals(1, cons.length);
42 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
43 assertEquals(true, Modifier.isPublic(ArrayUtils.class.getModifiers()));
44 assertEquals(false, Modifier.isFinal(ArrayUtils.class.getModifiers()));
50 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
51 assertTrue(Modifier.isPublic(ArrayUtils.class.getModifiers()));
52 assertFalse(Modifier.isFinal(ArrayUtils.class.getModifiers()));
4553 }
4654
4755 //-----------------------------------------------------------------------
56 @Test
4857 public void testToString() {
4958 assertEquals("{}", ArrayUtils.toString(null));
5059 assertEquals("{}", ArrayUtils.toString(new Object[0]));
6069 }
6170
6271 //-----------------------------------------------------------------------
72 @Test
6373 public void testHashCode() {
64 long[][] array1 = new long[][] {{2,5}, {4,5}};
65 long[][] array2 = new long[][] {{2,5}, {4,6}};
66 assertEquals(true, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array1));
67 assertEquals(false, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array2));
68
69 Object[] array3 = new Object[] {new String(new char[] {'A', 'B'})};
70 Object[] array4 = new Object[] {"AB"};
71 assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array3));
72 assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array4));
73
74 Object[] arrayA = new Object[] {new boolean[] {true, false}, new int[] {6, 7}};
75 Object[] arrayB = new Object[] {new boolean[] {true, false}, new int[] {6, 7}};
76 assertEquals(true, ArrayUtils.hashCode(arrayB) == ArrayUtils.hashCode(arrayA));
74 final long[][] array1 = new long[][] {{2,5}, {4,5}};
75 final long[][] array2 = new long[][] {{2,5}, {4,6}};
76 assertTrue(ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array1));
77 assertFalse(ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array2));
78
79 final Object[] array3 = new Object[] {new String(new char[] {'A', 'B'})};
80 final Object[] array4 = new Object[] {"AB"};
81 assertTrue(ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array3));
82 assertTrue(ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array4));
83
84 final Object[] arrayA = new Object[] {new boolean[] {true, false}, new int[] {6, 7}};
85 final Object[] arrayB = new Object[] {new boolean[] {true, false}, new int[] {6, 7}};
86 assertTrue(ArrayUtils.hashCode(arrayB) == ArrayUtils.hashCode(arrayA));
7787 }
7888
7989 //-----------------------------------------------------------------------
80 private void assertIsEquals(Object array1, Object array2, Object array3) {
81 assertEquals(true, ArrayUtils.isEquals(array1, array1));
82 assertEquals(true, ArrayUtils.isEquals(array2, array2));
83 assertEquals(true, ArrayUtils.isEquals(array3, array3));
84 assertEquals(false, ArrayUtils.isEquals(array1, array2));
85 assertEquals(false, ArrayUtils.isEquals(array2, array1));
86 assertEquals(false, ArrayUtils.isEquals(array1, array3));
87 assertEquals(false, ArrayUtils.isEquals(array3, array1));
88 assertEquals(false, ArrayUtils.isEquals(array1, array2));
89 assertEquals(false, ArrayUtils.isEquals(array2, array1));
90 }
91
90 private void assertIsEquals(final Object array1, final Object array2, final Object array3) {
91 assertTrue(ArrayUtils.isEquals(array1, array1));
92 assertTrue(ArrayUtils.isEquals(array2, array2));
93 assertTrue(ArrayUtils.isEquals(array3, array3));
94 assertFalse(ArrayUtils.isEquals(array1, array2));
95 assertFalse(ArrayUtils.isEquals(array2, array1));
96 assertFalse(ArrayUtils.isEquals(array1, array3));
97 assertFalse(ArrayUtils.isEquals(array3, array1));
98 assertFalse(ArrayUtils.isEquals(array1, array2));
99 assertFalse(ArrayUtils.isEquals(array2, array1));
100 }
101
102 @Test
92103 public void testIsEquals() {
93 long[][] larray1 = new long[][]{{2, 5}, {4, 5}};
94 long[][] larray2 = new long[][]{{2, 5}, {4, 6}};
95 long[] larray3 = new long[]{2, 5};
104 final long[][] larray1 = new long[][]{{2, 5}, {4, 5}};
105 final long[][] larray2 = new long[][]{{2, 5}, {4, 6}};
106 final long[] larray3 = new long[]{2, 5};
96107 this.assertIsEquals(larray1, larray2, larray3);
97108
98 int[][] iarray1 = new int[][]{{2, 5}, {4, 5}};
99 int[][] iarray2 = new int[][]{{2, 5}, {4, 6}};
100 int[] iarray3 = new int[]{2, 5};
109 final int[][] iarray1 = new int[][]{{2, 5}, {4, 5}};
110 final int[][] iarray2 = new int[][]{{2, 5}, {4, 6}};
111 final int[] iarray3 = new int[]{2, 5};
101112 this.assertIsEquals(iarray1, iarray2, iarray3);
102113
103 short[][] sarray1 = new short[][]{{2, 5}, {4, 5}};
104 short[][] sarray2 = new short[][]{{2, 5}, {4, 6}};
105 short[] sarray3 = new short[]{2, 5};
114 final short[][] sarray1 = new short[][]{{2, 5}, {4, 5}};
115 final short[][] sarray2 = new short[][]{{2, 5}, {4, 6}};
116 final short[] sarray3 = new short[]{2, 5};
106117 this.assertIsEquals(sarray1, sarray2, sarray3);
107118
108 float[][] farray1 = new float[][]{{2, 5}, {4, 5}};
109 float[][] farray2 = new float[][]{{2, 5}, {4, 6}};
110 float[] farray3 = new float[]{2, 5};
119 final float[][] farray1 = new float[][]{{2, 5}, {4, 5}};
120 final float[][] farray2 = new float[][]{{2, 5}, {4, 6}};
121 final float[] farray3 = new float[]{2, 5};
111122 this.assertIsEquals(farray1, farray2, farray3);
112123
113 double[][] darray1 = new double[][]{{2, 5}, {4, 5}};
114 double[][] darray2 = new double[][]{{2, 5}, {4, 6}};
115 double[] darray3 = new double[]{2, 5};
124 final double[][] darray1 = new double[][]{{2, 5}, {4, 5}};
125 final double[][] darray2 = new double[][]{{2, 5}, {4, 6}};
126 final double[] darray3 = new double[]{2, 5};
116127 this.assertIsEquals(darray1, darray2, darray3);
117128
118 byte[][] byteArray1 = new byte[][]{{2, 5}, {4, 5}};
119 byte[][] byteArray2 = new byte[][]{{2, 5}, {4, 6}};
120 byte[] byteArray3 = new byte[]{2, 5};
129 final byte[][] byteArray1 = new byte[][]{{2, 5}, {4, 5}};
130 final byte[][] byteArray2 = new byte[][]{{2, 5}, {4, 6}};
131 final byte[] byteArray3 = new byte[]{2, 5};
121132 this.assertIsEquals(byteArray1, byteArray2, byteArray3);
122133
123 char[][] charArray1 = new char[][]{{2, 5}, {4, 5}};
124 char[][] charArray2 = new char[][]{{2, 5}, {4, 6}};
125 char[] charArray3 = new char[]{2, 5};
134 final char[][] charArray1 = new char[][]{{2, 5}, {4, 5}};
135 final char[][] charArray2 = new char[][]{{2, 5}, {4, 6}};
136 final char[] charArray3 = new char[]{2, 5};
126137 this.assertIsEquals(charArray1, charArray2, charArray3);
127138
128 boolean[][] barray1 = new boolean[][]{{true, false}, {true, true}};
129 boolean[][] barray2 = new boolean[][]{{true, false}, {true, false}};
130 boolean[] barray3 = new boolean[]{false, true};
139 final boolean[][] barray1 = new boolean[][]{{true, false}, {true, true}};
140 final boolean[][] barray2 = new boolean[][]{{true, false}, {true, false}};
141 final boolean[] barray3 = new boolean[]{false, true};
131142 this.assertIsEquals(barray1, barray2, barray3);
132143
133 Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})};
134 Object[] array4 = new Object[]{"AB"};
135 assertEquals(true, ArrayUtils.isEquals(array3, array3));
136 assertEquals(true, ArrayUtils.isEquals(array3, array4));
137
138 assertEquals(true, ArrayUtils.isEquals(null, null));
139 assertEquals(false, ArrayUtils.isEquals(null, array4));
144 final Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})};
145 final Object[] array4 = new Object[]{"AB"};
146 assertTrue(ArrayUtils.isEquals(array3, array3));
147 assertTrue(ArrayUtils.isEquals(array3, array4));
148
149 assertTrue(ArrayUtils.isEquals(null, null));
150 assertFalse(ArrayUtils.isEquals(null, array4));
140151 }
141152
142153 //-----------------------------------------------------------------------
143154 /**
144155 * Tests generic array creation with parameters of same type.
145156 */
157 @Test
146158 public void testArrayCreation()
147159 {
148160 final String[] array = ArrayUtils.toArray("foo", "bar");
154166 /**
155167 * Tests generic array creation with general return type.
156168 */
169 @Test
157170 public void testArrayCreationWithGeneralReturnType()
158171 {
159172 final Object obj = ArrayUtils.toArray("foo", "bar");
163176 /**
164177 * Tests generic array creation with parameters of common base type.
165178 */
179 @Test
166180 public void testArrayCreationWithDifferentTypes()
167181 {
168182 final Number[] array = ArrayUtils.<Number>toArray(Integer.valueOf(42), Double.valueOf(Math.PI));
174188 /**
175189 * Tests generic array creation with generic type.
176190 */
191 @Test
177192 public void testIndirectArrayCreation()
178193 {
179194 final String[] array = toArrayPropagatingType("foo", "bar");
185200 /**
186201 * Tests generic empty array creation with generic type.
187202 */
203 @Test
188204 public void testEmptyArrayCreation()
189205 {
190206 final String[] array = ArrayUtils.<String>toArray();
194210 /**
195211 * Tests indirect generic empty array creation with generic type.
196212 */
213 @Test
197214 public void testIndirectEmptyArrayCreation()
198215 {
199216 final String[] array = ArrayUtilsTest.<String>toArrayPropagatingType();
206223 }
207224
208225 //-----------------------------------------------------------------------
226 @Test
209227 public void testToMap() {
210228 Map<?, ?> map = ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"hello", "world"}});
211229
216234 try {
217235 ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"short"}});
218236 fail("exception expected");
219 } catch (IllegalArgumentException ex) {}
237 } catch (final IllegalArgumentException ex) {}
220238 try {
221239 ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, "illegal type"});
222240 fail("exception expected");
223 } catch (IllegalArgumentException ex) {}
241 } catch (final IllegalArgumentException ex) {}
224242 try {
225243 ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, null});
226244 fail("exception expected");
227 } catch (IllegalArgumentException ex) {}
245 } catch (final IllegalArgumentException ex) {}
228246
229247 map = ArrayUtils.toMap(new Object[] {new Map.Entry<Object, Object>() {
248 @Override
230249 public Object getKey() {
231250 return "foo";
232251 }
252 @Override
233253 public Object getValue() {
234254 return "bar";
235255 }
236 public Object setValue(Object value) {
256 @Override
257 public Object setValue(final Object value) {
237258 throw new UnsupportedOperationException();
238259 }
239260 @Override
240 public boolean equals(Object o) {
261 public boolean equals(final Object o) {
241262 throw new UnsupportedOperationException();
242263 }
243264 @Override
249270 }
250271
251272 //-----------------------------------------------------------------------
273 @Test
252274 public void testClone() {
253 assertEquals(null, ArrayUtils.clone((Object[]) null));
275 assertArrayEquals(null, ArrayUtils.clone((Object[]) null));
254276 Object[] original1 = new Object[0];
255277 Object[] cloned1 = ArrayUtils.clone(original1);
256278 assertTrue(Arrays.equals(original1, cloned1));
257279 assertTrue(original1 != cloned1);
258280
259 StringBuffer buf = new StringBuffer("pick");
281 final StringBuffer buf = new StringBuffer("pick");
260282 original1 = new Object[] {buf, "a", new String[] {"stick"}};
261283 cloned1 = ArrayUtils.clone(original1);
262284 assertTrue(Arrays.equals(original1, cloned1));
266288 assertSame(original1[2], cloned1[2]);
267289 }
268290
291 @Test
269292 public void testCloneBoolean() {
270293 assertEquals(null, ArrayUtils.clone((boolean[]) null));
271 boolean[] original = new boolean[] {true, false};
272 boolean[] cloned = ArrayUtils.clone(original);
294 final boolean[] original = new boolean[] {true, false};
295 final boolean[] cloned = ArrayUtils.clone(original);
273296 assertTrue(Arrays.equals(original, cloned));
274297 assertTrue(original != cloned);
275298 }
276299
300 @Test
277301 public void testCloneLong() {
278302 assertEquals(null, ArrayUtils.clone((long[]) null));
279 long[] original = new long[] {0L, 1L};
280 long[] cloned = ArrayUtils.clone(original);
303 final long[] original = new long[] {0L, 1L};
304 final long[] cloned = ArrayUtils.clone(original);
281305 assertTrue(Arrays.equals(original, cloned));
282306 assertTrue(original != cloned);
283307 }
284308
309 @Test
285310 public void testCloneInt() {
286311 assertEquals(null, ArrayUtils.clone((int[]) null));
287 int[] original = new int[] {5, 8};
288 int[] cloned = ArrayUtils.clone(original);
312 final int[] original = new int[] {5, 8};
313 final int[] cloned = ArrayUtils.clone(original);
289314 assertTrue(Arrays.equals(original, cloned));
290315 assertTrue(original != cloned);
291316 }
292317
318 @Test
293319 public void testCloneShort() {
294320 assertEquals(null, ArrayUtils.clone((short[]) null));
295 short[] original = new short[] {1, 4};
296 short[] cloned = ArrayUtils.clone(original);
321 final short[] original = new short[] {1, 4};
322 final short[] cloned = ArrayUtils.clone(original);
297323 assertTrue(Arrays.equals(original, cloned));
298324 assertTrue(original != cloned);
299325 }
300326
327 @Test
301328 public void testCloneChar() {
302329 assertEquals(null, ArrayUtils.clone((char[]) null));
303 char[] original = new char[] {'a', '4'};
304 char[] cloned = ArrayUtils.clone(original);
330 final char[] original = new char[] {'a', '4'};
331 final char[] cloned = ArrayUtils.clone(original);
305332 assertTrue(Arrays.equals(original, cloned));
306333 assertTrue(original != cloned);
307334 }
308335
336 @Test
309337 public void testCloneByte() {
310338 assertEquals(null, ArrayUtils.clone((byte[]) null));
311 byte[] original = new byte[] {1, 6};
312 byte[] cloned = ArrayUtils.clone(original);
339 final byte[] original = new byte[] {1, 6};
340 final byte[] cloned = ArrayUtils.clone(original);
313341 assertTrue(Arrays.equals(original, cloned));
314342 assertTrue(original != cloned);
315343 }
316344
345 @Test
317346 public void testCloneDouble() {
318347 assertEquals(null, ArrayUtils.clone((double[]) null));
319 double[] original = new double[] {2.4d, 5.7d};
320 double[] cloned = ArrayUtils.clone(original);
348 final double[] original = new double[] {2.4d, 5.7d};
349 final double[] cloned = ArrayUtils.clone(original);
321350 assertTrue(Arrays.equals(original, cloned));
322351 assertTrue(original != cloned);
323352 }
324353
354 @Test
325355 public void testCloneFloat() {
326356 assertEquals(null, ArrayUtils.clone((float[]) null));
327 float[] original = new float[] {2.6f, 6.4f};
328 float[] cloned = ArrayUtils.clone(original);
357 final float[] original = new float[] {2.6f, 6.4f};
358 final float[] cloned = ArrayUtils.clone(original);
329359 assertTrue(Arrays.equals(original, cloned));
330360 assertTrue(original != cloned);
331361 }
332362
333363 //-----------------------------------------------------------------------
334364
365
366 @Test
367 public void testNullToEmptyBooleanNull() throws Exception {
368 assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.nullToEmpty((boolean[]) null));
369 }
370
371 @Test
372 public void testNullToEmptyBooleanEmptyArray() throws Exception {
373 final boolean[] empty = new boolean[]{};
374 final boolean[] result = ArrayUtils.nullToEmpty(empty);
375 assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, result);
376 assertNotSame(empty, result);
377 }
378
379 @Test
335380 public void testNullToEmptyBoolean() {
336 // Test null handling
337 assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.nullToEmpty((boolean[]) null));
338 // Test valid array handling
339 boolean[] original = new boolean[] {true, false};
381 final boolean[] original = new boolean[] {true, false};
340382 assertEquals(original, ArrayUtils.nullToEmpty(original));
341 // Test empty array handling
342 boolean[] empty = new boolean[]{};
343 boolean[] result = ArrayUtils.nullToEmpty(empty);
344 assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, result);
345 assertTrue(empty != result);
346 }
347
383 }
384
385 @Test
386 public void testNullToEmptyLongNull() throws Exception {
387 assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.nullToEmpty((long[]) null));
388 }
389
390 @Test
391 public void testNullToEmptyLongEmptyArray() throws Exception {
392 final long[] empty = new long[]{};
393 final long[] result = ArrayUtils.nullToEmpty(empty);
394 assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, result);
395 assertNotSame(empty, result);
396 }
397
398 @Test
348399 public void testNullToEmptyLong() {
349 // Test null handling
350 assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.nullToEmpty((long[]) null));
351 // Test valid array handling
352 long[] original = new long[] {1L, 2L};
400 final long[] original = new long[] {1L, 2L};
353401 assertEquals(original, ArrayUtils.nullToEmpty(original));
354 // Test empty array handling
355 long[] empty = new long[]{};
356 long[] result = ArrayUtils.nullToEmpty(empty);
357 assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, result);
358 assertTrue(empty != result);
359 }
360
402 }
403
404 @Test
405 public void testNullToEmptyIntNull() throws Exception {
406 assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.nullToEmpty((int[]) null));
407 }
408
409 @Test
410 public void testNullToEmptyIntEmptyArray() throws Exception {
411 final int[] empty = new int[]{};
412 final int[] result = ArrayUtils.nullToEmpty(empty);
413 assertEquals(ArrayUtils.EMPTY_INT_ARRAY, result);
414 assertNotSame(empty, result);
415 }
416
417 @Test
361418 public void testNullToEmptyInt() {
362 // Test null handling
363 assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.nullToEmpty((int[]) null));
364 // Test valid array handling
365 int[] original = new int[] {1, 2};
419 final int[] original = new int[] {1, 2};
366420 assertEquals(original, ArrayUtils.nullToEmpty(original));
367 // Test empty array handling
368 int[] empty = new int[]{};
369 int[] result = ArrayUtils.nullToEmpty(empty);
370 assertEquals(ArrayUtils.EMPTY_INT_ARRAY, result);
371 assertTrue(empty != result);
372 }
373
421 }
422
423 @Test
424 public void testNullToEmptyShortNull() throws Exception {
425 assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.nullToEmpty((short[]) null));
426 }
427
428 @Test
429 public void testNullToEmptyShortEmptyArray() throws Exception {
430 final short[] empty = new short[]{};
431 final short[] result = ArrayUtils.nullToEmpty(empty);
432 assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, result);
433 assertNotSame(empty, result);
434 }
435
436 @Test
374437 public void testNullToEmptyShort() {
375 // Test null handling
376 assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.nullToEmpty((short[]) null));
377 // Test valid array handling
378 short[] original = new short[] {1, 2};
438 final short[] original = new short[] {1, 2};
379439 assertEquals(original, ArrayUtils.nullToEmpty(original));
380 // Test empty array handling
381 short[] empty = new short[]{};
382 short[] result = ArrayUtils.nullToEmpty(empty);
383 assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, result);
384 assertTrue(empty != result);
385 }
386
440 }
441
442 @Test
443 public void testNullToEmptyCharNull() throws Exception {
444 assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.nullToEmpty((char[]) null));
445 }
446
447 @Test
448 public void testNullToEmptyCharEmptyArray() throws Exception {
449 final char[] empty = new char[]{};
450 final char[] result = ArrayUtils.nullToEmpty(empty);
451 assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, result);
452 assertNotSame(empty, result);
453 }
454
455 @Test
387456 public void testNullToEmptyChar() {
388 // Test null handling
389 assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.nullToEmpty((char[]) null));
390 // Test valid array handling
391 char[] original = new char[] {'a', 'b'};
457 final char[] original = new char[] {'a', 'b'};
392458 assertEquals(original, ArrayUtils.nullToEmpty(original));
393 // Test empty array handling
394 char[] empty = new char[]{};
395 char[] result = ArrayUtils.nullToEmpty(empty);
396 assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, result);
397 assertTrue(empty != result);
398 }
399
459 }
460
461 @Test
462 public void testNullToEmptyByteNull() throws Exception {
463 assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.nullToEmpty((byte[]) null));
464 }
465
466 @Test
467 public void testNullToEmptyByteEmptyArray() throws Exception {
468 final byte[] empty = new byte[]{};
469 final byte[] result = ArrayUtils.nullToEmpty(empty);
470 assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, result);
471 assertNotSame(empty, result);
472 }
473
474 @Test
400475 public void testNullToEmptyByte() {
401 // Test null handling
402 assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.nullToEmpty((byte[]) null));
403 // Test valid array handling
404 byte[] original = new byte[] {0x0F, 0x0E};
476 final byte[] original = new byte[] {0x0F, 0x0E};
405477 assertEquals(original, ArrayUtils.nullToEmpty(original));
406 // Test empty array handling
407 byte[] empty = new byte[]{};
408 byte[] result = ArrayUtils.nullToEmpty(empty);
409 assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, result);
410 assertTrue(empty != result);
411 }
412
478 }
479
480 @Test
481 public void testNullToEmptyDoubleNull() throws Exception {
482 assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.nullToEmpty((double[]) null));
483 }
484
485 @Test
486 public void testNullToEmptyDoubleEmptyArray() throws Exception {
487 final double[] empty = new double[]{};
488 final double[] result = ArrayUtils.nullToEmpty(empty);
489 assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, result);
490 assertNotSame(empty, result);
491 }
492
493 @Test
413494 public void testNullToEmptyDouble() {
414 // Test null handling
415 assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.nullToEmpty((double[]) null));
416 // Test valid array handling
417 double[] original = new double[] {1L, 2L};
495 final double[] original = new double[] {1L, 2L};
418496 assertEquals(original, ArrayUtils.nullToEmpty(original));
419 // Test empty array handling
420 double[] empty = new double[]{};
421 double[] result = ArrayUtils.nullToEmpty(empty);
422 assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, result);
423 assertTrue(empty != result);
424 }
425
497 }
498
499 @Test
500 public void testNullToEmptyFloatNull() throws Exception {
501 assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.nullToEmpty((float[]) null));
502 }
503
504 @Test
505 public void testNullToEmptyFloatEmptyArray() throws Exception {
506 final float[] empty = new float[]{};
507 final float[] result = ArrayUtils.nullToEmpty(empty);
508 assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, result);
509 assertNotSame(empty, result);
510 }
511
512 @Test
426513 public void testNullToEmptyFloat() {
427 // Test null handling
428 assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.nullToEmpty((float[]) null));
429 // Test valid array handling
430 float[] original = new float[] {2.6f, 3.8f};
514 final float[] original = new float[] {2.6f, 3.8f};
431515 assertEquals(original, ArrayUtils.nullToEmpty(original));
432 // Test empty array handling
433 float[] empty = new float[]{};
434 float[] result = ArrayUtils.nullToEmpty(empty);
435 assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, result);
436 assertTrue(empty != result);
437 }
438
516 }
517
518 @Test
519 public void testNullToEmptyObjectNull() throws Exception {
520 assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Object[]) null));
521 }
522
523 @Test
524 public void testNullToEmptyObjectEmptyArray() throws Exception {
525 final Object[] empty = new Object[]{};
526 final Object[] result = ArrayUtils.nullToEmpty(empty);
527 assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, result);
528 assertNotSame(empty, result);
529 }
530
531 @Test
439532 public void testNullToEmptyObject() {
440 // Test null handling
441 assertEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Object[]) null));
442 // Test valid array handling
443 Object[] original = new Object[] {true, false};
444 assertEquals(original, ArrayUtils.nullToEmpty(original));
445 // Test empty array handling
446 Object[] empty = new Object[]{};
447 Object[] result = ArrayUtils.nullToEmpty(empty);
448 assertEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, result);
449 assertTrue(empty != result);
450 }
451
533 final Object[] original = new Object[] {Boolean.TRUE, Boolean.FALSE};
534 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
535 }
536
537 @Test
538 public void testNullToEmptyClassNull() throws Exception {
539 assertArrayEquals(ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.nullToEmpty((Class<?>[]) null));
540 }
541
542 @Test
543 public void testNullToEmptyClassEmptyArray() throws Exception {
544 final Class<?>[] empty = {};
545 final Class<?>[] result = ArrayUtils.nullToEmpty(empty);
546 assertArrayEquals(ArrayUtils.EMPTY_CLASS_ARRAY, result);
547 assertNotSame(empty, result);
548 }
549
550 @Test
551 public void testNullToEmptyClass() {
552 final Class<?>[] original = { Object.class, String.class };
553 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
554 }
555
556 @Test
557 public void testNullToEmptyStringNull() throws Exception {
558 assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.nullToEmpty((String[]) null));
559 }
560
561 @Test
562 public void testNullToEmptyStringEmptyArray() throws Exception {
563 final String[] empty = new String[]{};
564 final String[] result = ArrayUtils.nullToEmpty(empty);
565 assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, result);
566 assertNotSame(empty, result);
567 }
568
569 @Test
452570 public void testNullToEmptyString() {
453 // Test null handling
454 assertEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.nullToEmpty((String[]) null));
455 // Test valid array handling
456 String[] original = new String[] {"abc", "def"};
457 assertEquals(original, ArrayUtils.nullToEmpty(original));
458 // Test empty array handling
459 String[] empty = new String[]{};
460 String[] result = ArrayUtils.nullToEmpty(empty);
461 assertEquals(ArrayUtils.EMPTY_STRING_ARRAY, result);
462 assertTrue(empty != result);
463 }
464
571 final String[] original = new String[] {"abc", "def"};
572 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
573 }
574
575 @Test
576 public void testNullToEmptyBooleanObjectNull() throws Exception {
577 assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Boolean[]) null));
578 }
579
580 @Test
581 public void testNullToEmptyBooleanObjectEmptyArray() throws Exception {
582 final Boolean[] empty = new Boolean[]{};
583 final Boolean[] result = ArrayUtils.nullToEmpty(empty);
584 assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, result);
585 assertNotSame(empty, result);
586 }
587
588 @Test
465589 public void testNullToEmptyBooleanObject() {
466 // Test null handling
467 assertEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Boolean[]) null));
468 // Test valid array handling
469 Boolean[] original = new Boolean[] {Boolean.TRUE, Boolean.FALSE};
470 assertEquals(original, ArrayUtils.nullToEmpty(original));
471 // Test empty array handling
472 Boolean[] empty = new Boolean[]{};
473 Boolean[] result = ArrayUtils.nullToEmpty(empty);
474 assertEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, result);
475 assertTrue(empty != result);
476 }
477
590 final Boolean[] original = new Boolean[] {Boolean.TRUE, Boolean.FALSE};
591 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
592 }
593
594 @Test
595 public void testNullToEmptyLongObjectNull() throws Exception {
596 assertArrayEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Long[]) null));
597 }
598
599 @Test
600 public void testNullToEmptyLongObjectEmptyArray() throws Exception {
601 final Long[] empty = new Long[]{};
602 final Long[] result = ArrayUtils.nullToEmpty(empty);
603 assertArrayEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, result);
604 assertNotSame(empty, result);
605 }
606
607 @Test
478608 public void testNullToEmptyLongObject() {
479 // Test null handling
480 assertEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Long[]) null));
481 // Test valid array handling
482 Long[] original = new Long[] {1L, 2L};
483 assertEquals(original, ArrayUtils.nullToEmpty(original));
484 // Test empty array handling
485 Long[] empty = new Long[]{};
486 Long[] result = ArrayUtils.nullToEmpty(empty);
487 assertEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, result);
488 assertTrue(empty != result);
489 }
490
609 @SuppressWarnings("boxing")
610 final Long[] original = new Long[] {1L, 2L};
611 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
612 }
613
614 @Test
615 public void testNullToEmptyIntObjectNull() throws Exception {
616 assertArrayEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Integer[]) null));
617 }
618
619 @Test
620 public void testNullToEmptyIntObjectEmptyArray() throws Exception {
621 final Integer[] empty = new Integer[]{};
622 final Integer[] result = ArrayUtils.nullToEmpty(empty);
623 assertArrayEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, result);
624 assertNotSame(empty, result);
625 }
626
627 @Test
491628 public void testNullToEmptyIntObject() {
492 // Test null handling
493 assertEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Integer[]) null));
494 // Test valid array handling
495 Integer[] original = new Integer[] {1, 2};
496 assertEquals(original, ArrayUtils.nullToEmpty(original));
497 // Test empty array handling
498 Integer[] empty = new Integer[]{};
499 Integer[] result = ArrayUtils.nullToEmpty(empty);
500 assertEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, result);
501 assertTrue(empty != result);
502 }
503
629 final Integer[] original = new Integer[] {1, 2};
630 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
631 }
632
633 @Test
634 public void testNullToEmptyShortObjectNull() throws Exception {
635 assertArrayEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Short[]) null));
636 }
637
638 @Test
639 public void testNullToEmptyShortObjectEmptyArray() throws Exception {
640 final Short[] empty = new Short[]{};
641 final Short[] result = ArrayUtils.nullToEmpty(empty);
642 assertArrayEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, result);
643 assertNotSame(empty, result);
644 }
645
646 @Test
504647 public void testNullToEmptyShortObject() {
505 // Test null handling
506 assertEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Short[]) null));
507 // Test valid array handling
508 Short[] original = new Short[] {1, 2};
509 assertEquals(original, ArrayUtils.nullToEmpty(original));
510 // Test empty array handling
511 Short[] empty = new Short[]{};
512 Short[] result = ArrayUtils.nullToEmpty(empty);
513 assertEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, result);
514 assertTrue(empty != result);
515 }
516
648 @SuppressWarnings("boxing")
649 final Short[] original = new Short[] {1, 2};
650 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
651 }
652
653 @Test
654 public void testNUllToEmptyCharObjectNull() throws Exception {
655 assertArrayEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Character[]) null));
656 }
657
658 @Test
659 public void testNullToEmptyCharObjectEmptyArray() throws Exception {
660 final Character[] empty = new Character[]{};
661 final Character[] result = ArrayUtils.nullToEmpty(empty);
662 assertArrayEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, result);
663 assertNotSame(empty, result);
664 }
665
666 @Test
517667 public void testNullToEmptyCharObject() {
518 // Test null handling
519 assertEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Character[]) null));
520 // Test valid array handling
521 Character[] original = new Character[] {'a', 'b'};
522 assertEquals(original, ArrayUtils.nullToEmpty(original));
523 // Test empty array handling
524 Character[] empty = new Character[]{};
525 Character[] result = ArrayUtils.nullToEmpty(empty);
526 assertEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, result);
527 assertTrue(empty != result);
528 }
529
668 final Character[] original = new Character[] {'a', 'b'};
669 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
670 }
671
672 @Test
673 public void testNullToEmptyByteObjectNull() throws Exception {
674 assertArrayEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Byte[]) null));
675 }
676
677 @Test
678 public void testNullToEmptyByteObjectEmptyArray() throws Exception {
679 final Byte[] empty = new Byte[]{};
680 final Byte[] result = ArrayUtils.nullToEmpty(empty);
681 assertArrayEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, result);
682 assertNotSame(empty, result);
683 }
684
685 @Test
530686 public void testNullToEmptyByteObject() {
531 // Test null handling
532 assertEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Byte[]) null));
533 // Test valid array handling
534 Byte[] original = new Byte[] {0x0F, 0x0E};
535 assertEquals(original, ArrayUtils.nullToEmpty(original));
536 // Test empty array handling
537 Byte[] empty = new Byte[]{};
538 Byte[] result = ArrayUtils.nullToEmpty(empty);
539 assertEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, result);
540 assertTrue(empty != result);
541 }
542
687 final Byte[] original = new Byte[] {0x0F, 0x0E};
688 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
689 }
690
691 @Test
692 public void testNullToEmptyDoubleObjectNull() throws Exception {
693 assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Double[]) null));
694 }
695
696 @Test
697 public void testNullToEmptyDoubleObjectEmptyArray() throws Exception {
698 final Double[] empty = new Double[]{};
699 final Double[] result = ArrayUtils.nullToEmpty(empty);
700 assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, result);
701 assertNotSame(empty, result);
702 }
703
704 @Test
543705 public void testNullToEmptyDoubleObject() {
544 // Test null handling
545 assertEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Double[]) null));
546 // Test valid array handling
547 Double[] original = new Double[] {1D, 2D};
548 assertEquals(original, ArrayUtils.nullToEmpty(original));
549 // Test empty array handling
550 Double[] empty = new Double[]{};
551 Double[] result = ArrayUtils.nullToEmpty(empty);
552 assertEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, result);
553 assertTrue(empty != result);
554 }
555
706 final Double[] original = new Double[] {1D, 2D};
707 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
708 }
709
710 @Test
711 public void testNullToEmptyFloatObjectNull() throws Exception {
712 assertArrayEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Float[]) null));
713 }
714
715 @Test
716 public void testNullToEmptyFloatObjectEmptyArray() throws Exception {
717 final Float[] empty = new Float[]{};
718 final Float[] result = ArrayUtils.nullToEmpty(empty);
719 assertArrayEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, result);
720 assertNotSame(empty, result);
721 }
722
723 @Test
556724 public void testNullToEmptyFloatObject() {
557 // Test null handling
558 assertEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Float[]) null));
559 // Test valid array handling
560 Float[] original = new Float[] {2.6f, 3.8f};
561 assertEquals(original, ArrayUtils.nullToEmpty(original));
562 // Test empty array handling
563 Float[] empty = new Float[]{};
564 Float[] result = ArrayUtils.nullToEmpty(empty);
565 assertEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, result);
566 assertTrue(empty != result);
725 final Float[] original = new Float[] {2.6f, 3.8f};
726 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
567727 }
568728
569729 //-----------------------------------------------------------------------
570730
731 @Test
571732 public void testSubarrayObject() {
572 Object[] nullArray = null;
573 Object[] objectArray = { "a", "b", "c", "d", "e", "f"};
733 final Object[] nullArray = null;
734 final Object[] objectArray = { "a", "b", "c", "d", "e", "f"};
574735
575736 assertEquals("0 start, mid end", "abcd",
576737 StringUtils.join(ArrayUtils.subarray(objectArray, 0, 4)));
598759 StringUtils.join(ArrayUtils.subarray(objectArray, -2, 12)));
599760
600761 // array type tests
601 Date[] dateArray = { new java.sql.Date(new Date().getTime()),
762 final Date[] dateArray = { new java.sql.Date(new Date().getTime()),
602763 new Date(), new Date(), new Date(), new Date() };
603764
604765 assertSame("Object type", Object.class,
609770 ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType());
610771 try {
611772 @SuppressWarnings("unused")
773 final
612774 java.sql.Date[] dummy = (java.sql.Date[])ArrayUtils.subarray(dateArray, 1,3);
613775 fail("Invalid downcast");
614 } catch (ClassCastException e) {}
615 }
616
776 } catch (final ClassCastException e) {}
777 }
778
779 @Test
617780 public void testSubarrayLong() {
618 long[] nullArray = null;
619 long[] array = { 999910, 999911, 999912, 999913, 999914, 999915 };
620 long[] leftSubarray = { 999910, 999911, 999912, 999913 };
621 long[] midSubarray = { 999911, 999912, 999913, 999914 };
622 long[] rightSubarray = { 999912, 999913, 999914, 999915 };
781 final long[] nullArray = null;
782 final long[] array = { 999910, 999911, 999912, 999913, 999914, 999915 };
783 final long[] leftSubarray = { 999910, 999911, 999912, 999913 };
784 final long[] midSubarray = { 999911, 999912, 999913, 999914 };
785 final long[] rightSubarray = { 999912, 999913, 999914, 999915 };
623786
624787 assertTrue("0 start, mid end",
625788 ArrayUtils.isEquals(leftSubarray,
690853
691854 }
692855
856 @Test
693857 public void testSubarrayInt() {
694 int[] nullArray = null;
695 int[] array = { 10, 11, 12, 13, 14, 15 };
696 int[] leftSubarray = { 10, 11, 12, 13 };
697 int[] midSubarray = { 11, 12, 13, 14 };
698 int[] rightSubarray = { 12, 13, 14, 15 };
858 final int[] nullArray = null;
859 final int[] array = { 10, 11, 12, 13, 14, 15 };
860 final int[] leftSubarray = { 10, 11, 12, 13 };
861 final int[] midSubarray = { 11, 12, 13, 14 };
862 final int[] rightSubarray = { 12, 13, 14, 15 };
699863
700864
701865 assertTrue("0 start, mid end",
767931
768932 }
769933
934 @Test
770935 public void testSubarrayShort() {
771 short[] nullArray = null;
772 short[] array = { 10, 11, 12, 13, 14, 15 };
773 short[] leftSubarray = { 10, 11, 12, 13 };
774 short[] midSubarray = { 11, 12, 13, 14 };
775 short[] rightSubarray = { 12, 13, 14, 15 };
936 final short[] nullArray = null;
937 final short[] array = { 10, 11, 12, 13, 14, 15 };
938 final short[] leftSubarray = { 10, 11, 12, 13 };
939 final short[] midSubarray = { 11, 12, 13, 14 };
940 final short[] rightSubarray = { 12, 13, 14, 15 };
776941
777942
778943 assertTrue("0 start, mid end",
8441009
8451010 }
8461011
1012 @Test
8471013 public void testSubarrChar() {
848 char[] nullArray = null;
849 char[] array = { 'a', 'b', 'c', 'd', 'e', 'f' };
850 char[] leftSubarray = { 'a', 'b', 'c', 'd', };
851 char[] midSubarray = { 'b', 'c', 'd', 'e', };
852 char[] rightSubarray = { 'c', 'd', 'e', 'f', };
1014 final char[] nullArray = null;
1015 final char[] array = { 'a', 'b', 'c', 'd', 'e', 'f' };
1016 final char[] leftSubarray = { 'a', 'b', 'c', 'd', };
1017 final char[] midSubarray = { 'b', 'c', 'd', 'e', };
1018 final char[] rightSubarray = { 'c', 'd', 'e', 'f', };
8531019
8541020
8551021 assertTrue("0 start, mid end",
9211087
9221088 }
9231089
1090 @Test
9241091 public void testSubarrayByte() {
925 byte[] nullArray = null;
926 byte[] array = { 10, 11, 12, 13, 14, 15 };
927 byte[] leftSubarray = { 10, 11, 12, 13 };
928 byte[] midSubarray = { 11, 12, 13, 14 };
929 byte[] rightSubarray = { 12, 13, 14, 15 };
1092 final byte[] nullArray = null;
1093 final byte[] array = { 10, 11, 12, 13, 14, 15 };
1094 final byte[] leftSubarray = { 10, 11, 12, 13 };
1095 final byte[] midSubarray = { 11, 12, 13, 14 };
1096 final byte[] rightSubarray = { 12, 13, 14, 15 };
9301097
9311098
9321099 assertTrue("0 start, mid end",
9981165
9991166 }
10001167
1168 @Test
10011169 public void testSubarrayDouble() {
1002 double[] nullArray = null;
1003 double[] array = { 10.123, 11.234, 12.345, 13.456, 14.567, 15.678 };
1004 double[] leftSubarray = { 10.123, 11.234, 12.345, 13.456, };
1005 double[] midSubarray = { 11.234, 12.345, 13.456, 14.567, };
1006 double[] rightSubarray = { 12.345, 13.456, 14.567, 15.678 };
1170 final double[] nullArray = null;
1171 final double[] array = { 10.123, 11.234, 12.345, 13.456, 14.567, 15.678 };
1172 final double[] leftSubarray = { 10.123, 11.234, 12.345, 13.456, };
1173 final double[] midSubarray = { 11.234, 12.345, 13.456, 14.567, };
1174 final double[] rightSubarray = { 12.345, 13.456, 14.567, 15.678 };
10071175
10081176
10091177 assertTrue("0 start, mid end",
10751243
10761244 }
10771245
1246 @Test
10781247 public void testSubarrayFloat() {
1079 float[] nullArray = null;
1080 float[] array = { 10, 11, 12, 13, 14, 15 };
1081 float[] leftSubarray = { 10, 11, 12, 13 };
1082 float[] midSubarray = { 11, 12, 13, 14 };
1083 float[] rightSubarray = { 12, 13, 14, 15 };
1248 final float[] nullArray = null;
1249 final float[] array = { 10, 11, 12, 13, 14, 15 };
1250 final float[] leftSubarray = { 10, 11, 12, 13 };
1251 final float[] midSubarray = { 11, 12, 13, 14 };
1252 final float[] rightSubarray = { 12, 13, 14, 15 };
10841253
10851254
10861255 assertTrue("0 start, mid end",
11521321
11531322 }
11541323
1324 @Test
11551325 public void testSubarrayBoolean() {
1156 boolean[] nullArray = null;
1157 boolean[] array = { true, true, false, true, false, true };
1158 boolean[] leftSubarray = { true, true, false, true };
1159 boolean[] midSubarray = { true, false, true, false };
1160 boolean[] rightSubarray = { false, true, false, true };
1326 final boolean[] nullArray = null;
1327 final boolean[] array = { true, true, false, true, false, true };
1328 final boolean[] leftSubarray = { true, true, false, true };
1329 final boolean[] midSubarray = { true, false, true, false };
1330 final boolean[] rightSubarray = { false, true, false, true };
11611331
11621332
11631333 assertTrue("0 start, mid end",
12301400 }
12311401
12321402 //-----------------------------------------------------------------------
1403 @Test
12331404 public void testSameLength() {
1234 Object[] nullArray = null;
1235 Object[] emptyArray = new Object[0];
1236 Object[] oneArray = new Object[] {"pick"};
1237 Object[] twoArray = new Object[] {"pick", "stick"};
1238
1239 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1240 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1241 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1242 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1243
1244 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1245 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1246 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1247 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1248
1249 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1250 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1251 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1252 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1253
1254 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1255 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1256 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1257 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1258 }
1259
1405 final Object[] nullArray = null;
1406 final Object[] emptyArray = new Object[0];
1407 final Object[] oneArray = new Object[] {"pick"};
1408 final Object[] twoArray = new Object[] {"pick", "stick"};
1409
1410 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1411 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1412 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1413 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1414
1415 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1416 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1417 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1418 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1419
1420 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1421 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1422 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1423 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1424
1425 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1426 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1427 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1428 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1429 }
1430
1431 @Test
12601432 public void testSameLengthBoolean() {
1261 boolean[] nullArray = null;
1262 boolean[] emptyArray = new boolean[0];
1263 boolean[] oneArray = new boolean[] {true};
1264 boolean[] twoArray = new boolean[] {true, false};
1265
1266 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1267 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1268 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1269 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1270
1271 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1272 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1273 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1274 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1275
1276 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1277 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1278 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1279 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1280
1281 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1282 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1283 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1284 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1285 }
1286
1433 final boolean[] nullArray = null;
1434 final boolean[] emptyArray = new boolean[0];
1435 final boolean[] oneArray = new boolean[] {true};
1436 final boolean[] twoArray = new boolean[] {true, false};
1437
1438 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1439 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1440 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1441 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1442
1443 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1444 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1445 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1446 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1447
1448 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1449 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1450 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1451 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1452
1453 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1454 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1455 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1456 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1457 }
1458
1459 @Test
12871460 public void testSameLengthLong() {
1288 long[] nullArray = null;
1289 long[] emptyArray = new long[0];
1290 long[] oneArray = new long[] {0L};
1291 long[] twoArray = new long[] {0L, 76L};
1292
1293 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1294 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1295 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1296 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1297
1298 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1299 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1300 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1301 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1302
1303 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1304 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1305 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1306 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1307
1308 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1309 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1310 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1311 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1312 }
1313
1461 final long[] nullArray = null;
1462 final long[] emptyArray = new long[0];
1463 final long[] oneArray = new long[] {0L};
1464 final long[] twoArray = new long[] {0L, 76L};
1465
1466 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1467 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1468 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1469 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1470
1471 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1472 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1473 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1474 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1475
1476 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1477 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1478 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1479 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1480
1481 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1482 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1483 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1484 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1485 }
1486
1487 @Test
13141488 public void testSameLengthInt() {
1315 int[] nullArray = null;
1316 int[] emptyArray = new int[0];
1317 int[] oneArray = new int[] {4};
1318 int[] twoArray = new int[] {5, 7};
1319
1320 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1321 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1322 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1323 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1324
1325 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1326 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1327 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1328 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1329
1330 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1331 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1332 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1333 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1334
1335 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1336 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1337 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1338 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1339 }
1340
1489 final int[] nullArray = null;
1490 final int[] emptyArray = new int[0];
1491 final int[] oneArray = new int[] {4};
1492 final int[] twoArray = new int[] {5, 7};
1493
1494 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1495 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1496 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1497 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1498
1499 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1500 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1501 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1502 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1503
1504 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1505 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1506 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1507 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1508
1509 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1510 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1511 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1512 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1513 }
1514
1515 @Test
13411516 public void testSameLengthShort() {
1342 short[] nullArray = null;
1343 short[] emptyArray = new short[0];
1344 short[] oneArray = new short[] {4};
1345 short[] twoArray = new short[] {6, 8};
1346
1347 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1348 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1349 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1350 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1351
1352 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1353 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1354 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1355 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1356
1357 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1358 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1359 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1360 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1361
1362 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1363 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1364 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1365 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1366 }
1367
1517 final short[] nullArray = null;
1518 final short[] emptyArray = new short[0];
1519 final short[] oneArray = new short[] {4};
1520 final short[] twoArray = new short[] {6, 8};
1521
1522 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1523 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1524 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1525 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1526
1527 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1528 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1529 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1530 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1531
1532 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1533 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1534 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1535 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1536
1537 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1538 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1539 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1540 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1541 }
1542
1543 @Test
13681544 public void testSameLengthChar() {
1369 char[] nullArray = null;
1370 char[] emptyArray = new char[0];
1371 char[] oneArray = new char[] {'f'};
1372 char[] twoArray = new char[] {'d', 't'};
1373
1374 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1375 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1376 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1377 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1378
1379 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1380 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1381 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1382 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1383
1384 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1385 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1386 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1387 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1388
1389 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1390 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1391 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1392 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1393 }
1394
1545 final char[] nullArray = null;
1546 final char[] emptyArray = new char[0];
1547 final char[] oneArray = new char[] {'f'};
1548 final char[] twoArray = new char[] {'d', 't'};
1549
1550 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1551 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1552 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1553 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1554
1555 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1556 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1557 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1558 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1559
1560 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1561 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1562 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1563 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1564
1565 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1566 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1567 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1568 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1569 }
1570
1571 @Test
13951572 public void testSameLengthByte() {
1396 byte[] nullArray = null;
1397 byte[] emptyArray = new byte[0];
1398 byte[] oneArray = new byte[] {3};
1399 byte[] twoArray = new byte[] {4, 6};
1400
1401 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1402 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1403 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1404 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1405
1406 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1407 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1408 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1409 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1410
1411 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1412 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1413 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1414 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1415
1416 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1417 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1418 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1419 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1420 }
1421
1573 final byte[] nullArray = null;
1574 final byte[] emptyArray = new byte[0];
1575 final byte[] oneArray = new byte[] {3};
1576 final byte[] twoArray = new byte[] {4, 6};
1577
1578 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1579 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1580 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1581 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1582
1583 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1584 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1585 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1586 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1587
1588 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1589 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1590 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1591 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1592
1593 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1594 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1595 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1596 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1597 }
1598
1599 @Test
14221600 public void testSameLengthDouble() {
1423 double[] nullArray = null;
1424 double[] emptyArray = new double[0];
1425 double[] oneArray = new double[] {1.3d};
1426 double[] twoArray = new double[] {4.5d, 6.3d};
1427
1428 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1429 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1430 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1431 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1432
1433 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1434 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1435 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1436 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1437
1438 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1439 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1440 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1441 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1442
1443 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1444 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1445 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1446 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1447 }
1448
1601 final double[] nullArray = null;
1602 final double[] emptyArray = new double[0];
1603 final double[] oneArray = new double[] {1.3d};
1604 final double[] twoArray = new double[] {4.5d, 6.3d};
1605
1606 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1607 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1608 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1609 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1610
1611 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1612 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1613 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1614 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1615
1616 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1617 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1618 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1619 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1620
1621 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1622 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1623 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1624 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
1625 }
1626
1627 @Test
14491628 public void testSameLengthFloat() {
1450 float[] nullArray = null;
1451 float[] emptyArray = new float[0];
1452 float[] oneArray = new float[] {2.5f};
1453 float[] twoArray = new float[] {6.4f, 5.8f};
1454
1455 assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray));
1456 assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray));
1457 assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray));
1458 assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray));
1459
1460 assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray));
1461 assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray));
1462 assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray));
1463 assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray));
1464
1465 assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray));
1466 assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray));
1467 assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray));
1468 assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray));
1469
1470 assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray));
1471 assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray));
1472 assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray));
1473 assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray));
1629 final float[] nullArray = null;
1630 final float[] emptyArray = new float[0];
1631 final float[] oneArray = new float[] {2.5f};
1632 final float[] twoArray = new float[] {6.4f, 5.8f};
1633
1634 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
1635 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
1636 assertFalse(ArrayUtils.isSameLength(nullArray, oneArray));
1637 assertFalse(ArrayUtils.isSameLength(nullArray, twoArray));
1638
1639 assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray));
1640 assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray));
1641 assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray));
1642 assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray));
1643
1644 assertFalse(ArrayUtils.isSameLength(oneArray, nullArray));
1645 assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray));
1646 assertTrue(ArrayUtils.isSameLength(oneArray, oneArray));
1647 assertFalse(ArrayUtils.isSameLength(oneArray, twoArray));
1648
1649 assertFalse(ArrayUtils.isSameLength(twoArray, nullArray));
1650 assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray));
1651 assertFalse(ArrayUtils.isSameLength(twoArray, oneArray));
1652 assertTrue(ArrayUtils.isSameLength(twoArray, twoArray));
14741653 }
14751654
14761655 //-----------------------------------------------------------------------
1656 @Test
14771657 public void testSameType() {
14781658 try {
14791659 ArrayUtils.isSameType(null, null);
14801660 fail();
1481 } catch (IllegalArgumentException ex) {}
1661 } catch (final IllegalArgumentException ex) {}
14821662 try {
14831663 ArrayUtils.isSameType(null, new Object[0]);
14841664 fail();
1485 } catch (IllegalArgumentException ex) {}
1665 } catch (final IllegalArgumentException ex) {}
14861666 try {
14871667 ArrayUtils.isSameType(new Object[0], null);
14881668 fail();
1489 } catch (IllegalArgumentException ex) {}
1490
1491 assertEquals(true, ArrayUtils.isSameType(new Object[0], new Object[0]));
1492 assertEquals(false, ArrayUtils.isSameType(new String[0], new Object[0]));
1493 assertEquals(true, ArrayUtils.isSameType(new String[0][0], new String[0][0]));
1494 assertEquals(false, ArrayUtils.isSameType(new String[0], new String[0][0]));
1495 assertEquals(false, ArrayUtils.isSameType(new String[0][0], new String[0]));
1669 } catch (final IllegalArgumentException ex) {}
1670
1671 assertTrue(ArrayUtils.isSameType(new Object[0], new Object[0]));
1672 assertFalse(ArrayUtils.isSameType(new String[0], new Object[0]));
1673 assertTrue(ArrayUtils.isSameType(new String[0][0], new String[0][0]));
1674 assertFalse(ArrayUtils.isSameType(new String[0], new String[0][0]));
1675 assertFalse(ArrayUtils.isSameType(new String[0][0], new String[0]));
14961676 }
14971677
14981678 //-----------------------------------------------------------------------
1679 @Test
14991680 public void testReverse() {
1500 StringBuffer str1 = new StringBuffer("pick");
1501 String str2 = "a";
1502 String[] str3 = new String[] {"stick"};
1503 String str4 = "up";
1681 final StringBuffer str1 = new StringBuffer("pick");
1682 final String str2 = "a";
1683 final String[] str3 = new String[] {"stick"};
1684 final String str4 = "up";
15041685
15051686 Object[] array = new Object[] {str1, str2, str3};
15061687 ArrayUtils.reverse(array);
15171698
15181699 array = null;
15191700 ArrayUtils.reverse(array);
1520 assertEquals(null, array);
1521 }
1522
1701 assertArrayEquals(null, array);
1702 }
1703
1704 @Test
15231705 public void testReverseLong() {
15241706 long[] array = new long[] {1L, 2L, 3L};
15251707 ArrayUtils.reverse(array);
15321714 assertEquals(null, array);
15331715 }
15341716
1717 @Test
15351718 public void testReverseInt() {
15361719 int[] array = new int[] {1, 2, 3};
15371720 ArrayUtils.reverse(array);
15441727 assertEquals(null, array);
15451728 }
15461729
1730 @Test
15471731 public void testReverseShort() {
15481732 short[] array = new short[] {1, 2, 3};
15491733 ArrayUtils.reverse(array);
15561740 assertEquals(null, array);
15571741 }
15581742
1743 @Test
15591744 public void testReverseChar() {
15601745 char[] array = new char[] {'a', 'f', 'C'};
15611746 ArrayUtils.reverse(array);
15681753 assertEquals(null, array);
15691754 }
15701755
1756 @Test
15711757 public void testReverseByte() {
15721758 byte[] array = new byte[] {2, 3, 4};
15731759 ArrayUtils.reverse(array);
15801766 assertEquals(null, array);
15811767 }
15821768
1769 @Test
15831770 public void testReverseDouble() {
15841771 double[] array = new double[] {0.3d, 0.4d, 0.5d};
15851772 ArrayUtils.reverse(array);
15921779 assertEquals(null, array);
15931780 }
15941781
1782 @Test
15951783 public void testReverseFloat() {
15961784 float[] array = new float[] {0.3f, 0.4f, 0.5f};
15971785 ArrayUtils.reverse(array);
16041792 assertEquals(null, array);
16051793 }
16061794
1795 @Test
16071796 public void testReverseBoolean() {
16081797 boolean[] array = new boolean[] {false, false, true};
16091798 ArrayUtils.reverse(array);
1610 assertEquals(array[0], true);
1611 assertEquals(array[1], false);
1612 assertEquals(array[2], false);
1799 assertTrue(array[0]);
1800 assertFalse(array[1]);
1801 assertFalse(array[2]);
16131802
16141803 array = null;
16151804 ArrayUtils.reverse(array);
16161805 assertEquals(null, array);
16171806 }
16181807
1808 @Test
1809 public void testReverseBooleanRange() {
1810 boolean[] array = new boolean[] {false, false, true};
1811 // The whole array
1812 ArrayUtils.reverse(array, 0, 3);
1813 assertTrue(array[0]);
1814 assertFalse(array[1]);
1815 assertFalse(array[2]);
1816 // a range
1817 array = new boolean[] {false, false, true};
1818 ArrayUtils.reverse(array, 0, 2);
1819 assertFalse(array[0]);
1820 assertFalse(array[1]);
1821 assertTrue(array[2]);
1822 // a range with a negative start
1823 array = new boolean[] {false, false, true};
1824 ArrayUtils.reverse(array, -1, 3);
1825 assertTrue(array[0]);
1826 assertFalse(array[1]);
1827 assertFalse(array[2]);
1828 // a range with a large stop idnex
1829 array = new boolean[] {false, false, true};
1830 ArrayUtils.reverse(array, -1, array.length + 1000);
1831 assertTrue(array[0]);
1832 assertFalse(array[1]);
1833 assertFalse(array[2]);
1834 // null
1835 array = null;
1836 ArrayUtils.reverse(array, 0, 3);
1837 assertEquals(null, array);
1838 }
1839
1840 @Test
1841 public void testReverseByteRange() {
1842 byte[] array = new byte[] {1, 2, 3};
1843 // The whole array
1844 ArrayUtils.reverse(array, 0, 3);
1845 assertEquals(3, array[0]);
1846 assertEquals(2, array[1]);
1847 assertEquals(1, array[2]);
1848 // a range
1849 array = new byte[] {1, 2, 3};
1850 ArrayUtils.reverse(array, 0, 2);
1851 assertEquals(2, array[0]);
1852 assertEquals(1, array[1]);
1853 assertEquals(3, array[2]);
1854 // a range with a negative start
1855 array = new byte[] {1, 2, 3};
1856 ArrayUtils.reverse(array, -1, 3);
1857 assertEquals(3, array[0]);
1858 assertEquals(2, array[1]);
1859 assertEquals(1, array[2]);
1860 // a range with a large stop idnex
1861 array = new byte[] {1, 2, 3};
1862 ArrayUtils.reverse(array, -1, array.length + 1000);
1863 assertEquals(3, array[0]);
1864 assertEquals(2, array[1]);
1865 assertEquals(1, array[2]);
1866 // null
1867 array = null;
1868 ArrayUtils.reverse(array, 0, 3);
1869 assertEquals(null, array);
1870 }
1871
1872 @Test
1873 public void testReverseCharRange() {
1874 char[] array = new char[] {1, 2, 3};
1875 // The whole array
1876 ArrayUtils.reverse(array, 0, 3);
1877 assertEquals(3, array[0]);
1878 assertEquals(2, array[1]);
1879 assertEquals(1, array[2]);
1880 // a range
1881 array = new char[] {1, 2, 3};
1882 ArrayUtils.reverse(array, 0, 2);
1883 assertEquals(2, array[0]);
1884 assertEquals(1, array[1]);
1885 assertEquals(3, array[2]);
1886 // a range with a negative start
1887 array = new char[] {1, 2, 3};
1888 ArrayUtils.reverse(array, -1, 3);
1889 assertEquals(3, array[0]);
1890 assertEquals(2, array[1]);
1891 assertEquals(1, array[2]);
1892 // a range with a large stop idnex
1893 array = new char[] {1, 2, 3};
1894 ArrayUtils.reverse(array, -1, array.length + 1000);
1895 assertEquals(3, array[0]);
1896 assertEquals(2, array[1]);
1897 assertEquals(1, array[2]);
1898 // null
1899 array = null;
1900 ArrayUtils.reverse(array, 0, 3);
1901 assertEquals(null, array);
1902 }
1903
1904 @Test
1905 public void testReverseDoubleRange() {
1906 double[] array = new double[] {1, 2, 3};
1907 // The whole array
1908 ArrayUtils.reverse(array, 0, 3);
1909 assertEquals(3, array[0], 0);
1910 assertEquals(2, array[1], 0);
1911 assertEquals(1, array[2], 0);
1912 // a range
1913 array = new double[] {1, 2, 3};
1914 ArrayUtils.reverse(array, 0, 2);
1915 assertEquals(2, array[0], 0);
1916 assertEquals(1, array[1], 0);
1917 assertEquals(3, array[2], 0);
1918 // a range with a negative start
1919 array = new double[] {1, 2, 3};
1920 ArrayUtils.reverse(array, -1, 3);
1921 assertEquals(3, array[0], 0);
1922 assertEquals(2, array[1], 0);
1923 assertEquals(1, array[2], 0);
1924 // a range with a large stop idnex
1925 array = new double[] {1, 2, 3};
1926 ArrayUtils.reverse(array, -1, array.length + 1000);
1927 assertEquals(3, array[0], 0);
1928 assertEquals(2, array[1], 0);
1929 assertEquals(1, array[2], 0);
1930 // null
1931 array = null;
1932 ArrayUtils.reverse(array, 0, 3);
1933 assertEquals(null, array);
1934 }
1935
1936 @Test
1937 public void testReverseFloatRange() {
1938 float[] array = new float[] {1, 2, 3};
1939 // The whole array
1940 ArrayUtils.reverse(array, 0, 3);
1941 assertEquals(3, array[0], 0);
1942 assertEquals(2, array[1], 0);
1943 assertEquals(1, array[2], 0);
1944 // a range
1945 array = new float[] {1, 2, 3};
1946 ArrayUtils.reverse(array, 0, 2);
1947 assertEquals(2, array[0], 0);
1948 assertEquals(1, array[1], 0);
1949 assertEquals(3, array[2], 0);
1950 // a range with a negative start
1951 array = new float[] {1, 2, 3};
1952 ArrayUtils.reverse(array, -1, 3);
1953 assertEquals(3, array[0], 0);
1954 assertEquals(2, array[1], 0);
1955 assertEquals(1, array[2], 0);
1956 // a range with a large stop idnex
1957 array = new float[] {1, 2, 3};
1958 ArrayUtils.reverse(array, -1, array.length + 1000);
1959 assertEquals(3, array[0], 0);
1960 assertEquals(2, array[1], 0);
1961 assertEquals(1, array[2], 0);
1962 // null
1963 array = null;
1964 ArrayUtils.reverse(array, 0, 3);
1965 assertEquals(null, array);
1966 }
1967
1968 @Test
1969 public void testReverseIntRange() {
1970 int[] array = new int[] {1, 2, 3};
1971 // The whole array
1972 ArrayUtils.reverse(array, 0, 3);
1973 assertEquals(3, array[0]);
1974 assertEquals(2, array[1]);
1975 assertEquals(1, array[2]);
1976 // a range
1977 array = new int[] {1, 2, 3};
1978 ArrayUtils.reverse(array, 0, 2);
1979 assertEquals(2, array[0]);
1980 assertEquals(1, array[1]);
1981 assertEquals(3, array[2]);
1982 // a range with a negative start
1983 array = new int[] {1, 2, 3};
1984 ArrayUtils.reverse(array, -1, 3);
1985 assertEquals(3, array[0]);
1986 assertEquals(2, array[1]);
1987 assertEquals(1, array[2]);
1988 // a range with a large stop idnex
1989 array = new int[] {1, 2, 3};
1990 ArrayUtils.reverse(array, -1, array.length + 1000);
1991 assertEquals(3, array[0]);
1992 assertEquals(2, array[1]);
1993 assertEquals(1, array[2]);
1994 // null
1995 array = null;
1996 ArrayUtils.reverse(array, 0, 3);
1997 assertEquals(null, array);
1998 }
1999
2000 @Test
2001 public void testReverseLongRange() {
2002 long[] array = new long[] {1, 2, 3};
2003 // The whole array
2004 ArrayUtils.reverse(array, 0, 3);
2005 assertEquals(3, array[0]);
2006 assertEquals(2, array[1]);
2007 assertEquals(1, array[2]);
2008 // a range
2009 array = new long[] {1, 2, 3};
2010 ArrayUtils.reverse(array, 0, 2);
2011 assertEquals(2, array[0]);
2012 assertEquals(1, array[1]);
2013 assertEquals(3, array[2]);
2014 // a range with a negative start
2015 array = new long[] {1, 2, 3};
2016 ArrayUtils.reverse(array, -1, 3);
2017 assertEquals(3, array[0]);
2018 assertEquals(2, array[1]);
2019 assertEquals(1, array[2]);
2020 // a range with a large stop idnex
2021 array = new long[] {1, 2, 3};
2022 ArrayUtils.reverse(array, -1, array.length + 1000);
2023 assertEquals(3, array[0]);
2024 assertEquals(2, array[1]);
2025 assertEquals(1, array[2]);
2026 // null
2027 array = null;
2028 ArrayUtils.reverse(array, 0, 3);
2029 assertEquals(null, array);
2030 }
2031
2032 @Test
2033 public void testReverseShortRange() {
2034 short[] array = new short[] {1, 2, 3};
2035 // The whole array
2036 ArrayUtils.reverse(array, 0, 3);
2037 assertEquals(3, array[0]);
2038 assertEquals(2, array[1]);
2039 assertEquals(1, array[2]);
2040 // a range
2041 array = new short[] {1, 2, 3};
2042 ArrayUtils.reverse(array, 0, 2);
2043 assertEquals(2, array[0]);
2044 assertEquals(1, array[1]);
2045 assertEquals(3, array[2]);
2046 // a range with a negative start
2047 array = new short[] {1, 2, 3};
2048 ArrayUtils.reverse(array, -1, 3);
2049 assertEquals(3, array[0]);
2050 assertEquals(2, array[1]);
2051 assertEquals(1, array[2]);
2052 // a range with a large stop idnex
2053 array = new short[] {1, 2, 3};
2054 ArrayUtils.reverse(array, -1, array.length + 1000);
2055 assertEquals(3, array[0]);
2056 assertEquals(2, array[1]);
2057 assertEquals(1, array[2]);
2058 // null
2059 array = null;
2060 ArrayUtils.reverse(array, 0, 3);
2061 assertEquals(null, array);
2062 }
2063
2064 @Test
2065 public void testReverseObjectRange() {
2066 String[] array = new String[] {"1", "2", "3"};
2067 // The whole array
2068 ArrayUtils.reverse(array, 0, 3);
2069 assertEquals("3", array[0]);
2070 assertEquals("2", array[1]);
2071 assertEquals("1", array[2]);
2072 // a range
2073 array = new String[] {"1", "2", "3"};
2074 ArrayUtils.reverse(array, 0, 2);
2075 assertEquals("2", array[0]);
2076 assertEquals("1", array[1]);
2077 assertEquals("3", array[2]);
2078 // a range with a negative start
2079 array = new String[] {"1", "2", "3"};
2080 ArrayUtils.reverse(array, -1, 3);
2081 assertEquals("3", array[0]);
2082 assertEquals("2", array[1]);
2083 assertEquals("1", array[2]);
2084 // a range with a large stop idnex
2085 array = new String[] {"1", "2", "3"};
2086 ArrayUtils.reverse(array, -1, array.length + 1000);
2087 assertEquals("3", array[0]);
2088 assertEquals("2", array[1]);
2089 assertEquals("1", array[2]);
2090 // null
2091 array = null;
2092 ArrayUtils.reverse(array, 0, 3);
2093 assertEquals(null, array);
2094 }
2095
2096
16192097 //-----------------------------------------------------------------------
2098 @Test
16202099 public void testIndexOf() {
1621 Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
2100 final Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
16222101 assertEquals(-1, ArrayUtils.indexOf(null, null));
16232102 assertEquals(-1, ArrayUtils.indexOf(null, "0"));
16242103 assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0"));
16302109 assertEquals(-1, ArrayUtils.indexOf(array, "notInArray"));
16312110 }
16322111
2112 @Test
16332113 public void testIndexOfWithStartIndex() {
1634 Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
2114 final Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
16352115 assertEquals(-1, ArrayUtils.indexOf(null, null, 2));
16362116 assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0", 0));
16372117 assertEquals(-1, ArrayUtils.indexOf(null, "0", 2));
16472127 assertEquals(-1, ArrayUtils.indexOf(array, "0", 8));
16482128 }
16492129
2130 @Test
16502131 public void testLastIndexOf() {
1651 Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
2132 final Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
16522133 assertEquals(-1, ArrayUtils.lastIndexOf(null, null));
16532134 assertEquals(-1, ArrayUtils.lastIndexOf(null, "0"));
16542135 assertEquals(5, ArrayUtils.lastIndexOf(array, "0"));
16592140 assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray"));
16602141 }
16612142
2143 @Test
16622144 public void testLastIndexOfWithStartIndex() {
1663 Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
2145 final Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
16642146 assertEquals(-1, ArrayUtils.lastIndexOf(null, null, 2));
16652147 assertEquals(-1, ArrayUtils.lastIndexOf(null, "0", 2));
16662148 assertEquals(0, ArrayUtils.lastIndexOf(array, "0", 2));
16762158 assertEquals(5, ArrayUtils.lastIndexOf(array, "0", 88));
16772159 }
16782160
2161 @Test
16792162 public void testContains() {
1680 Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
1681 assertEquals(false, ArrayUtils.contains(null, null));
1682 assertEquals(false, ArrayUtils.contains(null, "1"));
1683 assertEquals(true, ArrayUtils.contains(array, "0"));
1684 assertEquals(true, ArrayUtils.contains(array, "1"));
1685 assertEquals(true, ArrayUtils.contains(array, "2"));
1686 assertEquals(true, ArrayUtils.contains(array, "3"));
1687 assertEquals(true, ArrayUtils.contains(array, null));
1688 assertEquals(false, ArrayUtils.contains(array, "notInArray"));
2163 final Object[] array = new Object[] { "0", "1", "2", "3", null, "0" };
2164 assertFalse(ArrayUtils.contains(null, null));
2165 assertFalse(ArrayUtils.contains(null, "1"));
2166 assertTrue(ArrayUtils.contains(array, "0"));
2167 assertTrue(ArrayUtils.contains(array, "1"));
2168 assertTrue(ArrayUtils.contains(array, "2"));
2169 assertTrue(ArrayUtils.contains(array, "3"));
2170 assertTrue(ArrayUtils.contains(array, null));
2171 assertFalse(ArrayUtils.contains(array, "notInArray"));
16892172 }
16902173
16912174 //-----------------------------------------------------------------------
2175 @Test
16922176 public void testIndexOfLong() {
16932177 long[] array = null;
16942178 assertEquals(-1, ArrayUtils.indexOf(array, 0));
17002184 assertEquals(-1, ArrayUtils.indexOf(array, 99));
17012185 }
17022186
2187 @Test
17032188 public void testIndexOfLongWithStartIndex() {
17042189 long[] array = null;
17052190 assertEquals(-1, ArrayUtils.indexOf(array, 0, 2));
17132198 assertEquals(-1, ArrayUtils.indexOf(array, 0, 6));
17142199 }
17152200
2201 @Test
17162202 public void testLastIndexOfLong() {
17172203 long[] array = null;
17182204 assertEquals(-1, ArrayUtils.lastIndexOf(array, 0));
17242210 assertEquals(-1, ArrayUtils.lastIndexOf(array, 99));
17252211 }
17262212
2213 @Test
17272214 public void testLastIndexOfLongWithStartIndex() {
17282215 long[] array = null;
17292216 assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2));
17372224 assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88));
17382225 }
17392226
2227 @Test
17402228 public void testContainsLong() {
17412229 long[] array = null;
1742 assertEquals(false, ArrayUtils.contains(array, 1));
2230 assertFalse(ArrayUtils.contains(array, 1));
17432231 array = new long[] { 0, 1, 2, 3, 0 };
1744 assertEquals(true, ArrayUtils.contains(array, 0));
1745 assertEquals(true, ArrayUtils.contains(array, 1));
1746 assertEquals(true, ArrayUtils.contains(array, 2));
1747 assertEquals(true, ArrayUtils.contains(array, 3));
1748 assertEquals(false, ArrayUtils.contains(array, 99));
2232 assertTrue(ArrayUtils.contains(array, 0));
2233 assertTrue(ArrayUtils.contains(array, 1));
2234 assertTrue(ArrayUtils.contains(array, 2));
2235 assertTrue(ArrayUtils.contains(array, 3));
2236 assertFalse(ArrayUtils.contains(array, 99));
17492237 }
17502238
17512239 //-----------------------------------------------------------------------
2240 @Test
17522241 public void testIndexOfInt() {
17532242 int[] array = null;
17542243 assertEquals(-1, ArrayUtils.indexOf(array, 0));
17602249 assertEquals(-1, ArrayUtils.indexOf(array, 99));
17612250 }
17622251
2252 @Test
17632253 public void testIndexOfIntWithStartIndex() {
17642254 int[] array = null;
17652255 assertEquals(-1, ArrayUtils.indexOf(array, 0, 2));
17732263 assertEquals(-1, ArrayUtils.indexOf(array, 0, 6));
17742264 }
17752265
2266 @Test
17762267 public void testLastIndexOfInt() {
17772268 int[] array = null;
17782269 assertEquals(-1, ArrayUtils.lastIndexOf(array, 0));
17842275 assertEquals(-1, ArrayUtils.lastIndexOf(array, 99));
17852276 }
17862277
2278 @Test
17872279 public void testLastIndexOfIntWithStartIndex() {
17882280 int[] array = null;
17892281 assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2));
17972289 assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88));
17982290 }
17992291
2292 @Test
18002293 public void testContainsInt() {
18012294 int[] array = null;
1802 assertEquals(false, ArrayUtils.contains(array, 1));
2295 assertFalse(ArrayUtils.contains(array, 1));
18032296 array = new int[] { 0, 1, 2, 3, 0 };
1804 assertEquals(true, ArrayUtils.contains(array, 0));
1805 assertEquals(true, ArrayUtils.contains(array, 1));
1806 assertEquals(true, ArrayUtils.contains(array, 2));
1807 assertEquals(true, ArrayUtils.contains(array, 3));
1808 assertEquals(false, ArrayUtils.contains(array, 99));
2297 assertTrue(ArrayUtils.contains(array, 0));
2298 assertTrue(ArrayUtils.contains(array, 1));
2299 assertTrue(ArrayUtils.contains(array, 2));
2300 assertTrue(ArrayUtils.contains(array, 3));
2301 assertFalse(ArrayUtils.contains(array, 99));
18092302 }
18102303
18112304 //-----------------------------------------------------------------------
2305 @Test
18122306 public void testIndexOfShort() {
18132307 short[] array = null;
18142308 assertEquals(-1, ArrayUtils.indexOf(array, (short) 0));
18202314 assertEquals(-1, ArrayUtils.indexOf(array, (short) 99));
18212315 }
18222316
2317 @Test
18232318 public void testIndexOfShortWithStartIndex() {
18242319 short[] array = null;
18252320 assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 2));
18332328 assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 6));
18342329 }
18352330
2331 @Test
18362332 public void testLastIndexOfShort() {
18372333 short[] array = null;
18382334 assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0));
18442340 assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99));
18452341 }
18462342
2343 @Test
18472344 public void testLastIndexOfShortWithStartIndex() {
18482345 short[] array = null;
18492346 assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0, 2));
18572354 assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0, 88));
18582355 }
18592356
2357 @Test
18602358 public void testContainsShort() {
18612359 short[] array = null;
1862 assertEquals(false, ArrayUtils.contains(array, (short) 1));
2360 assertFalse(ArrayUtils.contains(array, (short) 1));
18632361 array = new short[] { 0, 1, 2, 3, 0 };
1864 assertEquals(true, ArrayUtils.contains(array, (short) 0));
1865 assertEquals(true, ArrayUtils.contains(array, (short) 1));
1866 assertEquals(true, ArrayUtils.contains(array, (short) 2));
1867 assertEquals(true, ArrayUtils.contains(array, (short) 3));
1868 assertEquals(false, ArrayUtils.contains(array, (short) 99));
2362 assertTrue(ArrayUtils.contains(array, (short) 0));
2363 assertTrue(ArrayUtils.contains(array, (short) 1));
2364 assertTrue(ArrayUtils.contains(array, (short) 2));
2365 assertTrue(ArrayUtils.contains(array, (short) 3));
2366 assertFalse(ArrayUtils.contains(array, (short) 99));
18692367 }
18702368
18712369 //-----------------------------------------------------------------------
2370 @Test
18722371 public void testIndexOfChar() {
18732372 char[] array = null;
18742373 assertEquals(-1, ArrayUtils.indexOf(array, 'a'));
18802379 assertEquals(-1, ArrayUtils.indexOf(array, 'e'));
18812380 }
18822381
2382 @Test
18832383 public void testIndexOfCharWithStartIndex() {
18842384 char[] array = null;
18852385 assertEquals(-1, ArrayUtils.indexOf(array, 'a', 2));
18932393 assertEquals(-1, ArrayUtils.indexOf(array, 'a', 6));
18942394 }
18952395
2396 @Test
18962397 public void testLastIndexOfChar() {
18972398 char[] array = null;
18982399 assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a'));
19042405 assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e'));
19052406 }
19062407
2408 @Test
19072409 public void testLastIndexOfCharWithStartIndex() {
19082410 char[] array = null;
19092411 assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a', 2));
19172419 assertEquals(4, ArrayUtils.lastIndexOf(array, 'a', 88));
19182420 }
19192421
2422 @Test
19202423 public void testContainsChar() {
19212424 char[] array = null;
1922 assertEquals(false, ArrayUtils.contains(array, 'b'));
2425 assertFalse(ArrayUtils.contains(array, 'b'));
19232426 array = new char[] { 'a', 'b', 'c', 'd', 'a' };
1924 assertEquals(true, ArrayUtils.contains(array, 'a'));
1925 assertEquals(true, ArrayUtils.contains(array, 'b'));
1926 assertEquals(true, ArrayUtils.contains(array, 'c'));
1927 assertEquals(true, ArrayUtils.contains(array, 'd'));
1928 assertEquals(false, ArrayUtils.contains(array, 'e'));
2427 assertTrue(ArrayUtils.contains(array, 'a'));
2428 assertTrue(ArrayUtils.contains(array, 'b'));
2429 assertTrue(ArrayUtils.contains(array, 'c'));
2430 assertTrue(ArrayUtils.contains(array, 'd'));
2431 assertFalse(ArrayUtils.contains(array, 'e'));
19292432 }
19302433
19312434 //-----------------------------------------------------------------------
2435 @Test
19322436 public void testIndexOfByte() {
19332437 byte[] array = null;
19342438 assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0));
19402444 assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99));
19412445 }
19422446
2447 @Test
19432448 public void testIndexOfByteWithStartIndex() {
19442449 byte[] array = null;
19452450 assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 2));
19532458 assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 6));
19542459 }
19552460
2461 @Test
19562462 public void testLastIndexOfByte() {
19572463 byte[] array = null;
19582464 assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0));
19642470 assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99));
19652471 }
19662472
2473 @Test
19672474 public void testLastIndexOfByteWithStartIndex() {
19682475 byte[] array = null;
19692476 assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0, 2));
19772484 assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0, 88));
19782485 }
19792486
2487 @Test
19802488 public void testContainsByte() {
19812489 byte[] array = null;
1982 assertEquals(false, ArrayUtils.contains(array, (byte) 1));
2490 assertFalse(ArrayUtils.contains(array, (byte) 1));
19832491 array = new byte[] { 0, 1, 2, 3, 0 };
1984 assertEquals(true, ArrayUtils.contains(array, (byte) 0));
1985 assertEquals(true, ArrayUtils.contains(array, (byte) 1));
1986 assertEquals(true, ArrayUtils.contains(array, (byte) 2));
1987 assertEquals(true, ArrayUtils.contains(array, (byte) 3));
1988 assertEquals(false, ArrayUtils.contains(array, (byte) 99));
2492 assertTrue(ArrayUtils.contains(array, (byte) 0));
2493 assertTrue(ArrayUtils.contains(array, (byte) 1));
2494 assertTrue(ArrayUtils.contains(array, (byte) 2));
2495 assertTrue(ArrayUtils.contains(array, (byte) 3));
2496 assertFalse(ArrayUtils.contains(array, (byte) 99));
19892497 }
19902498
19912499 //-----------------------------------------------------------------------
19922500 @SuppressWarnings("cast")
2501 @Test
19932502 public void testIndexOfDouble() {
19942503 double[] array = null;
19952504 assertEquals(-1, ArrayUtils.indexOf(array, (double) 0));
20052514 }
20062515
20072516 @SuppressWarnings("cast")
2517 @Test
20082518 public void testIndexOfDoubleTolerance() {
20092519 double[] array = null;
20102520 assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0));
20182528 }
20192529
20202530 @SuppressWarnings("cast")
2531 @Test
20212532 public void testIndexOfDoubleWithStartIndex() {
20222533 double[] array = null;
20232534 assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2));
20332544 }
20342545
20352546 @SuppressWarnings("cast")
2547 @Test
20362548 public void testIndexOfDoubleWithStartIndexTolerance() {
20372549 double[] array = null;
20382550 assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0));
20502562 }
20512563
20522564 @SuppressWarnings("cast")
2565 @Test
20532566 public void testLastIndexOfDouble() {
20542567 double[] array = null;
20552568 assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0));
20642577 }
20652578
20662579 @SuppressWarnings("cast")
2580 @Test
20672581 public void testLastIndexOfDoubleTolerance() {
20682582 double[] array = null;
20692583 assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0));
20772591 }
20782592
20792593 @SuppressWarnings("cast")
2594 @Test
20802595 public void testLastIndexOfDoubleWithStartIndex() {
20812596 double[] array = null;
20822597 assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2));
20932608 }
20942609
20952610 @SuppressWarnings("cast")
2611 @Test
20962612 public void testLastIndexOfDoubleWithStartIndexTolerance() {
20972613 double[] array = null;
20982614 assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0));
21102626 }
21112627
21122628 @SuppressWarnings("cast")
2629 @Test
21132630 public void testContainsDouble() {
21142631 double[] array = null;
2115 assertEquals(false, ArrayUtils.contains(array, (double) 1));
2632 assertFalse(ArrayUtils.contains(array, (double) 1));
21162633 array = new double[] { 0, 1, 2, 3, 0 };
2117 assertEquals(true, ArrayUtils.contains(array, (double) 0));
2118 assertEquals(true, ArrayUtils.contains(array, (double) 1));
2119 assertEquals(true, ArrayUtils.contains(array, (double) 2));
2120 assertEquals(true, ArrayUtils.contains(array, (double) 3));
2121 assertEquals(false, ArrayUtils.contains(array, (double) 99));
2634 assertTrue(ArrayUtils.contains(array, (double) 0));
2635 assertTrue(ArrayUtils.contains(array, (double) 1));
2636 assertTrue(ArrayUtils.contains(array, (double) 2));
2637 assertTrue(ArrayUtils.contains(array, (double) 3));
2638 assertFalse(ArrayUtils.contains(array, (double) 99));
21222639 }
21232640
21242641 @SuppressWarnings("cast")
2642 @Test
21252643 public void testContainsDoubleTolerance() {
21262644 double[] array = null;
2127 assertEquals(false, ArrayUtils.contains(array, (double) 1, (double) 0));
2645 assertFalse(ArrayUtils.contains(array, (double) 1, (double) 0));
21282646 array = new double[] { 0, 1, 2, 3, 0 };
2129 assertEquals(false, ArrayUtils.contains(array, (double) 4.0, (double) 0.33));
2130 assertEquals(false, ArrayUtils.contains(array, (double) 2.5, (double) 0.49));
2131 assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.50));
2132 assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.51));
2647 assertFalse(ArrayUtils.contains(array, (double) 4.0, (double) 0.33));
2648 assertFalse(ArrayUtils.contains(array, (double) 2.5, (double) 0.49));
2649 assertTrue(ArrayUtils.contains(array, (double) 2.5, (double) 0.50));
2650 assertTrue(ArrayUtils.contains(array, (double) 2.5, (double) 0.51));
21332651 }
21342652
21352653 //-----------------------------------------------------------------------
21362654 @SuppressWarnings("cast")
2655 @Test
21372656 public void testIndexOfFloat() {
21382657 float[] array = null;
21392658 assertEquals(-1, ArrayUtils.indexOf(array, (float) 0));
21482667 }
21492668
21502669 @SuppressWarnings("cast")
2670 @Test
21512671 public void testIndexOfFloatWithStartIndex() {
21522672 float[] array = null;
21532673 assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2));
21642684 }
21652685
21662686 @SuppressWarnings("cast")
2687 @Test
21672688 public void testLastIndexOfFloat() {
21682689 float[] array = null;
21692690 assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0));
21782699 }
21792700
21802701 @SuppressWarnings("cast")
2702 @Test
21812703 public void testLastIndexOfFloatWithStartIndex() {
21822704 float[] array = null;
21832705 assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2));
21942716 }
21952717
21962718 @SuppressWarnings("cast")
2719 @Test
21972720 public void testContainsFloat() {
21982721 float[] array = null;
2199 assertEquals(false, ArrayUtils.contains(array, (float) 1));
2722 assertFalse(ArrayUtils.contains(array, (float) 1));
22002723 array = new float[] { 0, 1, 2, 3, 0 };
2201 assertEquals(true, ArrayUtils.contains(array, (float) 0));
2202 assertEquals(true, ArrayUtils.contains(array, (float) 1));
2203 assertEquals(true, ArrayUtils.contains(array, (float) 2));
2204 assertEquals(true, ArrayUtils.contains(array, (float) 3));
2205 assertEquals(false, ArrayUtils.contains(array, (float) 99));
2724 assertTrue(ArrayUtils.contains(array, (float) 0));
2725 assertTrue(ArrayUtils.contains(array, (float) 1));
2726 assertTrue(ArrayUtils.contains(array, (float) 2));
2727 assertTrue(ArrayUtils.contains(array, (float) 3));
2728 assertFalse(ArrayUtils.contains(array, (float) 99));
22062729 }
22072730
22082731 //-----------------------------------------------------------------------
2732 @Test
22092733 public void testIndexOfBoolean() {
22102734 boolean[] array = null;
22112735 assertEquals(-1, ArrayUtils.indexOf(array, true));
22182742 assertEquals(-1, ArrayUtils.indexOf(array, false));
22192743 }
22202744
2745 @Test
22212746 public void testIndexOfBooleanWithStartIndex() {
22222747 boolean[] array = null;
22232748 assertEquals(-1, ArrayUtils.indexOf(array, true, 2));
22332758 assertEquals(-1, ArrayUtils.indexOf(array, false, -1));
22342759 }
22352760
2761 @Test
22362762 public void testLastIndexOfBoolean() {
22372763 boolean[] array = null;
22382764 assertEquals(-1, ArrayUtils.lastIndexOf(array, true));
22452771 assertEquals(-1, ArrayUtils.lastIndexOf(array, false));
22462772 }
22472773
2774 @Test
22482775 public void testLastIndexOfBooleanWithStartIndex() {
22492776 boolean[] array = null;
22502777 assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2));
22602787 assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1));
22612788 }
22622789
2790 @Test
22632791 public void testContainsBoolean() {
22642792 boolean[] array = null;
2265 assertEquals(false, ArrayUtils.contains(array, true));
2793 assertFalse(ArrayUtils.contains(array, true));
22662794 array = new boolean[] { true, false, true };
2267 assertEquals(true, ArrayUtils.contains(array, true));
2268 assertEquals(true, ArrayUtils.contains(array, false));
2795 assertTrue(ArrayUtils.contains(array, true));
2796 assertTrue(ArrayUtils.contains(array, false));
22692797 array = new boolean[] { true, true };
2270 assertEquals(true, ArrayUtils.contains(array, true));
2271 assertEquals(false, ArrayUtils.contains(array, false));
2798 assertTrue(ArrayUtils.contains(array, true));
2799 assertFalse(ArrayUtils.contains(array, false));
22722800 }
22732801
22742802 // testToPrimitive/Object for boolean
22752803 // -----------------------------------------------------------------------
2804 @Test
22762805 public void testToPrimitive_boolean() {
22772806 final Boolean[] b = null;
22782807 assertEquals(null, ArrayUtils.toPrimitive(b));
22852814 try {
22862815 ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null});
22872816 fail();
2288 } catch (NullPointerException ex) {}
2289 }
2290
2817 } catch (final NullPointerException ex) {}
2818 }
2819
2820 @Test
22912821 public void testToPrimitive_boolean_boolean() {
22922822 assertEquals(null, ArrayUtils.toPrimitive(null, false));
22932823 assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0], false));
23052835 );
23062836 }
23072837
2838 @Test
23082839 public void testToObject_boolean() {
23092840 final boolean[] b = null;
2310 assertEquals(null, ArrayUtils.toObject(b));
2841 assertArrayEquals(null, ArrayUtils.toObject(b));
23112842 assertSame(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.toObject(new boolean[0]));
23122843 assertTrue(Arrays.equals(
23132844 new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE},
23172848
23182849 // testToPrimitive/Object for byte
23192850 // -----------------------------------------------------------------------
2851 @Test
23202852 public void testToPrimitive_char() {
23212853 final Character[] b = null;
23222854 assertEquals(null, ArrayUtils.toPrimitive(b));
23322864 try {
23332865 ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE), null});
23342866 fail();
2335 } catch (NullPointerException ex) {}
2336 }
2337
2867 } catch (final NullPointerException ex) {}
2868 }
2869
2870 @Test
23382871 public void testToPrimitive_char_char() {
23392872 final Character[] b = null;
23402873 assertEquals(null, ArrayUtils.toPrimitive(b, Character.MIN_VALUE));
23562889 );
23572890 }
23582891
2892 @Test
23592893 public void testToObject_char() {
23602894 final char[] b = null;
2361 assertEquals(null, ArrayUtils.toObject(b));
2895 assertArrayEquals(null, ArrayUtils.toObject(b));
23622896
23632897 assertSame(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY,
23642898 ArrayUtils.toObject(new char[0]));
23732907
23742908 // testToPrimitive/Object for byte
23752909 // -----------------------------------------------------------------------
2910 @Test
23762911 public void testToPrimitive_byte() {
23772912 final Byte[] b = null;
23782913 assertEquals(null, ArrayUtils.toPrimitive(b));
23882923 try {
23892924 ArrayUtils.toPrimitive(new Byte[] {Byte.valueOf(Byte.MIN_VALUE), null});
23902925 fail();
2391 } catch (NullPointerException ex) {}
2392 }
2393
2926 } catch (final NullPointerException ex) {}
2927 }
2928
2929 @Test
23942930 public void testToPrimitive_byte_byte() {
23952931 final Byte[] b = null;
23962932 assertEquals(null, ArrayUtils.toPrimitive(b, Byte.MIN_VALUE));
24122948 );
24132949 }
24142950
2951 @Test
24152952 public void testToObject_byte() {
24162953 final byte[] b = null;
2417 assertEquals(null, ArrayUtils.toObject(b));
2954 assertArrayEquals(null, ArrayUtils.toObject(b));
24182955
24192956 assertSame(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY,
24202957 ArrayUtils.toObject(new byte[0]));
24292966
24302967 // testToPrimitive/Object for short
24312968 // -----------------------------------------------------------------------
2969 @Test
24322970 public void testToPrimitive_short() {
24332971 final Short[] b = null;
24342972 assertEquals(null, ArrayUtils.toPrimitive(b));
24442982 try {
24452983 ArrayUtils.toPrimitive(new Short[] {Short.valueOf(Short.MIN_VALUE), null});
24462984 fail();
2447 } catch (NullPointerException ex) {}
2448 }
2449
2985 } catch (final NullPointerException ex) {}
2986 }
2987
2988 @Test
24502989 public void testToPrimitive_short_short() {
24512990 final Short[] s = null;
24522991 assertEquals(null, ArrayUtils.toPrimitive(s, Short.MIN_VALUE));
24673006 );
24683007 }
24693008
3009 @Test
24703010 public void testToObject_short() {
24713011 final short[] b = null;
2472 assertEquals(null, ArrayUtils.toObject(b));
3012 assertArrayEquals(null, ArrayUtils.toObject(b));
24733013
24743014 assertSame(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY,
24753015 ArrayUtils.toObject(new short[0]));
24843024
24853025 // testToPrimitive/Object for int
24863026 // -----------------------------------------------------------------------
3027 @Test
24873028 public void testToPrimitive_int() {
24883029 final Integer[] b = null;
24893030 assertEquals(null, ArrayUtils.toPrimitive(b));
24973038 try {
24983039 ArrayUtils.toPrimitive(new Integer[] {Integer.valueOf(Integer.MIN_VALUE), null});
24993040 fail();
2500 } catch (NullPointerException ex) {}
3041 } catch (final NullPointerException ex) {}
25013042 }
25023043
3044 @Test
25033045 public void testToPrimitive_int_int() {
25043046 final Long[] l = null;
25053047 assertEquals(null, ArrayUtils.toPrimitive(l, Integer.MIN_VALUE));
25163058 );
25173059 }
25183060
3061 @Test
25193062 public void testToPrimitive_intNull() {
2520 Integer[] iArray = null;
3063 final Integer[] iArray = null;
25213064 assertEquals(null, ArrayUtils.toPrimitive(iArray, Integer.MIN_VALUE));
25223065 }
25233066
3067 @Test
25243068 public void testToObject_int() {
25253069 final int[] b = null;
2526 assertEquals(null, ArrayUtils.toObject(b));
3070 assertArrayEquals(null, ArrayUtils.toObject(b));
25273071
25283072 assertSame(
25293073 ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY,
25413085
25423086 // testToPrimitive/Object for long
25433087 // -----------------------------------------------------------------------
3088 @Test
25443089 public void testToPrimitive_long() {
25453090 final Long[] b = null;
25463091 assertEquals(null, ArrayUtils.toPrimitive(b));
25573102 try {
25583103 ArrayUtils.toPrimitive(new Long[] {Long.valueOf(Long.MIN_VALUE), null});
25593104 fail();
2560 } catch (NullPointerException ex) {}
3105 } catch (final NullPointerException ex) {}
25613106 }
25623107
3108 @Test
25633109 public void testToPrimitive_long_long() {
25643110 final Long[] l = null;
25653111 assertEquals(null, ArrayUtils.toPrimitive(l, Long.MIN_VALUE));
25793125 );
25803126 }
25813127
3128 @Test
25823129 public void testToObject_long() {
25833130 final long[] b = null;
2584 assertEquals(null, ArrayUtils.toObject(b));
3131 assertArrayEquals(null, ArrayUtils.toObject(b));
25853132
25863133 assertSame(
25873134 ArrayUtils.EMPTY_LONG_OBJECT_ARRAY,
25993146
26003147 // testToPrimitive/Object for float
26013148 // -----------------------------------------------------------------------
3149 @Test
26023150 public void testToPrimitive_float() {
26033151 final Float[] b = null;
26043152 assertEquals(null, ArrayUtils.toPrimitive(b));
26153163 try {
26163164 ArrayUtils.toPrimitive(new Float[] {Float.valueOf(Float.MIN_VALUE), null});
26173165 fail();
2618 } catch (NullPointerException ex) {}
3166 } catch (final NullPointerException ex) {}
26193167 }
26203168
3169 @Test
26213170 public void testToPrimitive_float_float() {
26223171 final Float[] l = null;
26233172 assertEquals(null, ArrayUtils.toPrimitive(l, Float.MIN_VALUE));
26373186 );
26383187 }
26393188
3189 @Test
26403190 public void testToObject_float() {
26413191 final float[] b = null;
2642 assertEquals(null, ArrayUtils.toObject(b));
3192 assertArrayEquals(null, ArrayUtils.toObject(b));
26433193
26443194 assertSame(
26453195 ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY,
26573207
26583208 // testToPrimitive/Object for double
26593209 // -----------------------------------------------------------------------
3210 @Test
26603211 public void testToPrimitive_double() {
26613212 final Double[] b = null;
26623213 assertEquals(null, ArrayUtils.toPrimitive(b));
26733224 try {
26743225 ArrayUtils.toPrimitive(new Float[] {Float.valueOf(Float.MIN_VALUE), null});
26753226 fail();
2676 } catch (NullPointerException ex) {}
3227 } catch (final NullPointerException ex) {}
26773228 }
26783229
3230 @Test
26793231 public void testToPrimitive_double_double() {
26803232 final Double[] l = null;
26813233 assertEquals(null, ArrayUtils.toPrimitive(l, Double.MIN_VALUE));
26953247 );
26963248 }
26973249
3250 @Test
26983251 public void testToObject_double() {
26993252 final double[] b = null;
2700 assertEquals(null, ArrayUtils.toObject(b));
3253 assertArrayEquals(null, ArrayUtils.toObject(b));
27013254
27023255 assertSame(
27033256 ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY,
27173270 /**
27183271 * Test for {@link ArrayUtils#isEmpty(java.lang.Object[])}.
27193272 */
3273 @Test
27203274 public void testIsEmptyObject() {
2721 Object[] emptyArray = new Object[] {};
2722 Object[] notEmptyArray = new Object[] { new String("Value") };
2723 assertEquals(true, ArrayUtils.isEmpty((Object[])null));
2724 assertEquals(true, ArrayUtils.isEmpty(emptyArray));
2725 assertEquals(false, ArrayUtils.isEmpty(notEmptyArray));
3275 final Object[] emptyArray = new Object[] {};
3276 final Object[] notEmptyArray = new Object[] { new String("Value") };
3277 assertTrue(ArrayUtils.isEmpty((Object[])null));
3278 assertTrue(ArrayUtils.isEmpty(emptyArray));
3279 assertFalse(ArrayUtils.isEmpty(notEmptyArray));
27263280 }
27273281
27283282 /**
27353289 * {@link ArrayUtils#isEmpty(float[])} and
27363290 * {@link ArrayUtils#isEmpty(boolean[])}.
27373291 */
3292 @Test
27383293 public void testIsEmptyPrimitives() {
2739 long[] emptyLongArray = new long[] {};
2740 long[] notEmptyLongArray = new long[] { 1L };
2741 assertEquals(true, ArrayUtils.isEmpty((long[])null));
2742 assertEquals(true, ArrayUtils.isEmpty(emptyLongArray));
2743 assertEquals(false, ArrayUtils.isEmpty(notEmptyLongArray));
2744
2745 int[] emptyIntArray = new int[] {};
2746 int[] notEmptyIntArray = new int[] { 1 };
2747 assertEquals(true, ArrayUtils.isEmpty((int[])null));
2748 assertEquals(true, ArrayUtils.isEmpty(emptyIntArray));
2749 assertEquals(false, ArrayUtils.isEmpty(notEmptyIntArray));
2750
2751 short[] emptyShortArray = new short[] {};
2752 short[] notEmptyShortArray = new short[] { 1 };
2753 assertEquals(true, ArrayUtils.isEmpty((short[])null));
2754 assertEquals(true, ArrayUtils.isEmpty(emptyShortArray));
2755 assertEquals(false, ArrayUtils.isEmpty(notEmptyShortArray));
2756
2757 char[] emptyCharArray = new char[] {};
2758 char[] notEmptyCharArray = new char[] { 1 };
2759 assertEquals(true, ArrayUtils.isEmpty((char[])null));
2760 assertEquals(true, ArrayUtils.isEmpty(emptyCharArray));
2761 assertEquals(false, ArrayUtils.isEmpty(notEmptyCharArray));
2762
2763 byte[] emptyByteArray = new byte[] {};
2764 byte[] notEmptyByteArray = new byte[] { 1 };
2765 assertEquals(true, ArrayUtils.isEmpty((byte[])null));
2766 assertEquals(true, ArrayUtils.isEmpty(emptyByteArray));
2767 assertEquals(false, ArrayUtils.isEmpty(notEmptyByteArray));
2768
2769 double[] emptyDoubleArray = new double[] {};
2770 double[] notEmptyDoubleArray = new double[] { 1.0 };
2771 assertEquals(true, ArrayUtils.isEmpty((double[])null));
2772 assertEquals(true, ArrayUtils.isEmpty(emptyDoubleArray));
2773 assertEquals(false, ArrayUtils.isEmpty(notEmptyDoubleArray));
2774
2775 float[] emptyFloatArray = new float[] {};
2776 float[] notEmptyFloatArray = new float[] { 1.0F };
2777 assertEquals(true, ArrayUtils.isEmpty((float[])null));
2778 assertEquals(true, ArrayUtils.isEmpty(emptyFloatArray));
2779 assertEquals(false, ArrayUtils.isEmpty(notEmptyFloatArray));
2780
2781 boolean[] emptyBooleanArray = new boolean[] {};
2782 boolean[] notEmptyBooleanArray = new boolean[] { true };
2783 assertEquals(true, ArrayUtils.isEmpty((boolean[])null));
2784 assertEquals(true, ArrayUtils.isEmpty(emptyBooleanArray));
2785 assertEquals(false, ArrayUtils.isEmpty(notEmptyBooleanArray));
3294 final long[] emptyLongArray = new long[] {};
3295 final long[] notEmptyLongArray = new long[] { 1L };
3296 assertTrue(ArrayUtils.isEmpty((long[])null));
3297 assertTrue(ArrayUtils.isEmpty(emptyLongArray));
3298 assertFalse(ArrayUtils.isEmpty(notEmptyLongArray));
3299
3300 final int[] emptyIntArray = new int[] {};
3301 final int[] notEmptyIntArray = new int[] { 1 };
3302 assertTrue(ArrayUtils.isEmpty((int[])null));
3303 assertTrue(ArrayUtils.isEmpty(emptyIntArray));
3304 assertFalse(ArrayUtils.isEmpty(notEmptyIntArray));
3305
3306 final short[] emptyShortArray = new short[] {};
3307 final short[] notEmptyShortArray = new short[] { 1 };
3308 assertTrue(ArrayUtils.isEmpty((short[])null));
3309 assertTrue(ArrayUtils.isEmpty(emptyShortArray));
3310 assertFalse(ArrayUtils.isEmpty(notEmptyShortArray));
3311
3312 final char[] emptyCharArray = new char[] {};
3313 final char[] notEmptyCharArray = new char[] { 1 };
3314 assertTrue(ArrayUtils.isEmpty((char[])null));
3315 assertTrue(ArrayUtils.isEmpty(emptyCharArray));
3316 assertFalse(ArrayUtils.isEmpty(notEmptyCharArray));
3317
3318 final byte[] emptyByteArray = new byte[] {};
3319 final byte[] notEmptyByteArray = new byte[] { 1 };
3320 assertTrue(ArrayUtils.isEmpty((byte[])null));
3321 assertTrue(ArrayUtils.isEmpty(emptyByteArray));
3322 assertFalse(ArrayUtils.isEmpty(notEmptyByteArray));
3323
3324 final double[] emptyDoubleArray = new double[] {};
3325 final double[] notEmptyDoubleArray = new double[] { 1.0 };
3326 assertTrue(ArrayUtils.isEmpty((double[])null));
3327 assertTrue(ArrayUtils.isEmpty(emptyDoubleArray));
3328 assertFalse(ArrayUtils.isEmpty(notEmptyDoubleArray));
3329
3330 final float[] emptyFloatArray = new float[] {};
3331 final float[] notEmptyFloatArray = new float[] { 1.0F };
3332 assertTrue(ArrayUtils.isEmpty((float[])null));
3333 assertTrue(ArrayUtils.isEmpty(emptyFloatArray));
3334 assertFalse(ArrayUtils.isEmpty(notEmptyFloatArray));
3335
3336 final boolean[] emptyBooleanArray = new boolean[] {};
3337 final boolean[] notEmptyBooleanArray = new boolean[] { true };
3338 assertTrue(ArrayUtils.isEmpty((boolean[])null));
3339 assertTrue(ArrayUtils.isEmpty(emptyBooleanArray));
3340 assertFalse(ArrayUtils.isEmpty(notEmptyBooleanArray));
27863341 }
27873342
27883343 /**
27893344 * Test for {@link ArrayUtils#isNotEmpty(java.lang.Object[])}.
27903345 */
3346 @Test
27913347 public void testIsNotEmptyObject() {
2792 Object[] emptyArray = new Object[] {};
2793 Object[] notEmptyArray = new Object[] { new String("Value") };
3348 final Object[] emptyArray = new Object[] {};
3349 final Object[] notEmptyArray = new Object[] { new String("Value") };
27943350 assertFalse(ArrayUtils.isNotEmpty((Object[])null));
27953351 assertFalse(ArrayUtils.isNotEmpty(emptyArray));
27963352 assertTrue(ArrayUtils.isNotEmpty(notEmptyArray));
28063362 * {@link ArrayUtils#isNotEmpty(float[])} and
28073363 * {@link ArrayUtils#isNotEmpty(boolean[])}.
28083364 */
3365 @Test
28093366 public void testIsNotEmptyPrimitives() {
2810 long[] emptyLongArray = new long[] {};
2811 long[] notEmptyLongArray = new long[] { 1L };
3367 final long[] emptyLongArray = new long[] {};
3368 final long[] notEmptyLongArray = new long[] { 1L };
28123369 assertFalse(ArrayUtils.isNotEmpty((long[])null));
28133370 assertFalse(ArrayUtils.isNotEmpty(emptyLongArray));
28143371 assertTrue(ArrayUtils.isNotEmpty(notEmptyLongArray));
28153372
2816 int[] emptyIntArray = new int[] {};
2817 int[] notEmptyIntArray = new int[] { 1 };
3373 final int[] emptyIntArray = new int[] {};
3374 final int[] notEmptyIntArray = new int[] { 1 };
28183375 assertFalse(ArrayUtils.isNotEmpty((int[])null));
28193376 assertFalse(ArrayUtils.isNotEmpty(emptyIntArray));
28203377 assertTrue(ArrayUtils.isNotEmpty(notEmptyIntArray));
28213378
2822 short[] emptyShortArray = new short[] {};
2823 short[] notEmptyShortArray = new short[] { 1 };
3379 final short[] emptyShortArray = new short[] {};
3380 final short[] notEmptyShortArray = new short[] { 1 };
28243381 assertFalse(ArrayUtils.isNotEmpty((short[])null));
28253382 assertFalse(ArrayUtils.isNotEmpty(emptyShortArray));
28263383 assertTrue(ArrayUtils.isNotEmpty(notEmptyShortArray));
28273384
2828 char[] emptyCharArray = new char[] {};
2829 char[] notEmptyCharArray = new char[] { 1 };
3385 final char[] emptyCharArray = new char[] {};
3386 final char[] notEmptyCharArray = new char[] { 1 };
28303387 assertFalse(ArrayUtils.isNotEmpty((char[])null));
28313388 assertFalse(ArrayUtils.isNotEmpty(emptyCharArray));
28323389 assertTrue(ArrayUtils.isNotEmpty(notEmptyCharArray));
28333390
2834 byte[] emptyByteArray = new byte[] {};
2835 byte[] notEmptyByteArray = new byte[] { 1 };
3391 final byte[] emptyByteArray = new byte[] {};
3392 final byte[] notEmptyByteArray = new byte[] { 1 };
28363393 assertFalse(ArrayUtils.isNotEmpty((byte[])null));
28373394 assertFalse(ArrayUtils.isNotEmpty(emptyByteArray));
28383395 assertTrue(ArrayUtils.isNotEmpty(notEmptyByteArray));
28393396
2840 double[] emptyDoubleArray = new double[] {};
2841 double[] notEmptyDoubleArray = new double[] { 1.0 };
3397 final double[] emptyDoubleArray = new double[] {};
3398 final double[] notEmptyDoubleArray = new double[] { 1.0 };
28423399 assertFalse(ArrayUtils.isNotEmpty((double[])null));
28433400 assertFalse(ArrayUtils.isNotEmpty(emptyDoubleArray));
28443401 assertTrue(ArrayUtils.isNotEmpty(notEmptyDoubleArray));
28453402
2846 float[] emptyFloatArray = new float[] {};
2847 float[] notEmptyFloatArray = new float[] { 1.0F };
3403 final float[] emptyFloatArray = new float[] {};
3404 final float[] notEmptyFloatArray = new float[] { 1.0F };
28483405 assertFalse(ArrayUtils.isNotEmpty((float[])null));
28493406 assertFalse(ArrayUtils.isNotEmpty(emptyFloatArray));
28503407 assertTrue(ArrayUtils.isNotEmpty(notEmptyFloatArray));
28513408
2852 boolean[] emptyBooleanArray = new boolean[] {};
2853 boolean[] notEmptyBooleanArray = new boolean[] { true };
3409 final boolean[] emptyBooleanArray = new boolean[] {};
3410 final boolean[] notEmptyBooleanArray = new boolean[] { true };
28543411 assertFalse(ArrayUtils.isNotEmpty((boolean[])null));
28553412 assertFalse(ArrayUtils.isNotEmpty(emptyBooleanArray));
28563413 assertTrue(ArrayUtils.isNotEmpty(notEmptyBooleanArray));
28573414 }
28583415 // ------------------------------------------------------------------------
3416 @Test
28593417 public void testGetLength() {
28603418 assertEquals(0, ArrayUtils.getLength(null));
28613419
2862 Object[] emptyObjectArray = new Object[0];
2863 Object[] notEmptyObjectArray = new Object[] {"aValue"};
3420 final Object[] emptyObjectArray = new Object[0];
3421 final Object[] notEmptyObjectArray = new Object[] {"aValue"};
28643422 assertEquals(0, ArrayUtils.getLength((Object[]) null));
28653423 assertEquals(0, ArrayUtils.getLength(emptyObjectArray));
28663424 assertEquals(1, ArrayUtils.getLength(notEmptyObjectArray));
28673425
2868 int[] emptyIntArray = new int[] {};
2869 int[] notEmptyIntArray = new int[] { 1 };
3426 final int[] emptyIntArray = new int[] {};
3427 final int[] notEmptyIntArray = new int[] { 1 };
28703428 assertEquals(0, ArrayUtils.getLength((int[]) null));
28713429 assertEquals(0, ArrayUtils.getLength(emptyIntArray));
28723430 assertEquals(1, ArrayUtils.getLength(notEmptyIntArray));
28733431
2874 short[] emptyShortArray = new short[] {};
2875 short[] notEmptyShortArray = new short[] { 1 };
3432 final short[] emptyShortArray = new short[] {};
3433 final short[] notEmptyShortArray = new short[] { 1 };
28763434 assertEquals(0, ArrayUtils.getLength((short[]) null));
28773435 assertEquals(0, ArrayUtils.getLength(emptyShortArray));
28783436 assertEquals(1, ArrayUtils.getLength(notEmptyShortArray));
28793437
2880 char[] emptyCharArray = new char[] {};
2881 char[] notEmptyCharArray = new char[] { 1 };
3438 final char[] emptyCharArray = new char[] {};
3439 final char[] notEmptyCharArray = new char[] { 1 };
28823440 assertEquals(0, ArrayUtils.getLength((char[]) null));
28833441 assertEquals(0, ArrayUtils.getLength(emptyCharArray));
28843442 assertEquals(1, ArrayUtils.getLength(notEmptyCharArray));
28853443
2886 byte[] emptyByteArray = new byte[] {};
2887 byte[] notEmptyByteArray = new byte[] { 1 };
3444 final byte[] emptyByteArray = new byte[] {};
3445 final byte[] notEmptyByteArray = new byte[] { 1 };
28883446 assertEquals(0, ArrayUtils.getLength((byte[]) null));
28893447 assertEquals(0, ArrayUtils.getLength(emptyByteArray));
28903448 assertEquals(1, ArrayUtils.getLength(notEmptyByteArray));
28913449
2892 double[] emptyDoubleArray = new double[] {};
2893 double[] notEmptyDoubleArray = new double[] { 1.0 };
3450 final double[] emptyDoubleArray = new double[] {};
3451 final double[] notEmptyDoubleArray = new double[] { 1.0 };
28943452 assertEquals(0, ArrayUtils.getLength((double[]) null));
28953453 assertEquals(0, ArrayUtils.getLength(emptyDoubleArray));
28963454 assertEquals(1, ArrayUtils.getLength(notEmptyDoubleArray));
28973455
2898 float[] emptyFloatArray = new float[] {};
2899 float[] notEmptyFloatArray = new float[] { 1.0F };
3456 final float[] emptyFloatArray = new float[] {};
3457 final float[] notEmptyFloatArray = new float[] { 1.0F };
29003458 assertEquals(0, ArrayUtils.getLength((float[]) null));
29013459 assertEquals(0, ArrayUtils.getLength(emptyFloatArray));
29023460 assertEquals(1, ArrayUtils.getLength(notEmptyFloatArray));
29033461
2904 boolean[] emptyBooleanArray = new boolean[] {};
2905 boolean[] notEmptyBooleanArray = new boolean[] { true };
3462 final boolean[] emptyBooleanArray = new boolean[] {};
3463 final boolean[] notEmptyBooleanArray = new boolean[] { true };
29063464 assertEquals(0, ArrayUtils.getLength((boolean[]) null));
29073465 assertEquals(0, ArrayUtils.getLength(emptyBooleanArray));
29083466 assertEquals(1, ArrayUtils.getLength(notEmptyBooleanArray));
29103468 try {
29113469 ArrayUtils.getLength("notAnArray");
29123470 fail("IllegalArgumentException should have been thrown");
2913 } catch (IllegalArgumentException e) {}
3471 } catch (final IllegalArgumentException e) {}
29143472 }
29153473
29163474 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import junit.framework.TestCase;
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertTrue;
21
22 import org.junit.Test;
1923
2024 /**
2125 * Class to test BitField functionality
2226 *
23 * @version $Id: BitFieldTest.java 1199894 2011-11-09 17:53:59Z ggregory $
27 * @version $Id: BitFieldTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2428 */
25 public class BitFieldTest extends TestCase {
29 public class BitFieldTest {
2630
2731 private static final BitField bf_multi = new BitField(0x3F80);
2832 private static final BitField bf_single = new BitField(0x4000);
2933 private static final BitField bf_zero = new BitField(0);
3034
3135 /**
32 * Constructor BitFieldTest
33 *
34 * @param name
35 */
36 public BitFieldTest(String name) {
37 super(name);
38 }
39
40 /**
4136 * test the getValue() method
4237 */
38 @Test
4339 public void testGetValue() {
4440 assertEquals(bf_multi.getValue(-1), 127);
4541 assertEquals(bf_multi.getValue(0), 0);
5248 /**
5349 * test the getShortValue() method
5450 */
51 @Test
5552 public void testGetShortValue() {
5653 assertEquals(bf_multi.getShortValue((short) - 1), (short) 127);
5754 assertEquals(bf_multi.getShortValue((short) 0), (short) 0);
6461 /**
6562 * test the getRawValue() method
6663 */
64 @Test
6765 public void testGetRawValue() {
6866 assertEquals(bf_multi.getRawValue(-1), 0x3F80);
6967 assertEquals(bf_multi.getRawValue(0), 0);
7674 /**
7775 * test the getShortRawValue() method
7876 */
77 @Test
7978 public void testGetShortRawValue() {
8079 assertEquals(bf_multi.getShortRawValue((short) - 1), (short) 0x3F80);
8180 assertEquals(bf_multi.getShortRawValue((short) 0), (short) 0);
8887 /**
8988 * test the isSet() method
9089 */
90 @Test
9191 public void testIsSet() {
9292 assertTrue(!bf_multi.isSet(0));
9393 assertTrue(!bf_zero.isSet(0));
104104 /**
105105 * test the isAllSet() method
106106 */
107 @Test
107108 public void testIsAllSet() {
108109 for (int j = 0; j < 0x3F80; j += 0x80) {
109110 assertTrue(!bf_multi.isAllSet(j));
117118 /**
118119 * test the setValue() method
119120 */
121 @Test
120122 public void testSetValue() {
121123 for (int j = 0; j < 128; j++) {
122124 assertEquals(bf_multi.getValue(bf_multi.setValue(0, j)), j);
141143 /**
142144 * test the setShortValue() method
143145 */
146 @Test
144147 public void testSetShortValue() {
145148 for (int j = 0; j < 128; j++) {
146149 assertEquals(bf_multi.getShortValue(bf_multi.setShortValue((short) 0, (short) j)), (short) j);
162165 assertEquals(bf_single.setShortValue((short) 0x4000, (short) 2), (short) 0);
163166 }
164167
168 @Test
165169 public void testByte() {
166170 assertEquals(0, new BitField(0).setByteBoolean((byte) 0, true));
167171 assertEquals(1, new BitField(1).setByteBoolean((byte) 0, true));
182186 assertEquals(0, new BitField(64).setByteBoolean((byte) 64, false));
183187 assertEquals(0, new BitField(128).setByteBoolean((byte) 128, false));
184188 assertEquals(-2, new BitField(1).setByteBoolean((byte) 255, false));
185 byte clearedBit = new BitField(0x40).setByteBoolean((byte) - 63, false);
186
187 assertEquals(false, new BitField(0x40).isSet(clearedBit));
189 final byte clearedBit = new BitField(0x40).setByteBoolean((byte) - 63, false);
190
191 assertFalse(new BitField(0x40).isSet(clearedBit));
188192 }
189193
190194 /**
191195 * test the clear() method
192196 */
197 @Test
193198 public void testClear() {
194199 assertEquals(bf_multi.clear(-1), 0xFFFFC07F);
195200 assertEquals(bf_single.clear(-1), 0xFFFFBFFF);
199204 /**
200205 * test the clearShort() method
201206 */
207 @Test
202208 public void testClearShort() {
203209 assertEquals(bf_multi.clearShort((short) - 1), (short) 0xC07F);
204210 assertEquals(bf_single.clearShort((short) - 1), (short) 0xBFFF);
208214 /**
209215 * test the set() method
210216 */
217 @Test
211218 public void testSet() {
212219 assertEquals(bf_multi.set(0), 0x3F80);
213220 assertEquals(bf_single.set(0), 0x4000);
217224 /**
218225 * test the setShort() method
219226 */
227 @Test
220228 public void testSetShort() {
221229 assertEquals(bf_multi.setShort((short) 0), (short) 0x3F80);
222230 assertEquals(bf_single.setShort((short) 0), (short) 0x4000);
226234 /**
227235 * test the setBoolean() method
228236 */
237 @Test
229238 public void testSetBoolean() {
230239 assertEquals(bf_multi.set(0), bf_multi.setBoolean(0, true));
231240 assertEquals(bf_single.set(0), bf_single.setBoolean(0, true));
238247 /**
239248 * test the setShortBoolean() method
240249 */
250 @Test
241251 public void testSetShortBoolean() {
242252 assertEquals(bf_multi.setShort((short) 0), bf_multi.setShortBoolean((short) 0, true));
243253 assertEquals(bf_single.setShort((short) 0), bf_single.setShortBoolean((short) 0, true));
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.*;
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertSame;
22 import static org.junit.Assert.assertTrue;
1923
2024 import java.lang.reflect.Constructor;
2125 import java.lang.reflect.Modifier;
2529 /**
2630 * Unit tests {@link org.apache.commons.lang3.BooleanUtils}.
2731 *
28 * @version $Id: BooleanUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
32 * @version $Id: BooleanUtilsTest.java 1534738 2013-10-22 19:23:21Z britter $
2933 */
3034 public class BooleanUtilsTest {
3135
3337 @Test
3438 public void testConstructor() {
3539 assertNotNull(new BooleanUtils());
36 Constructor<?>[] cons = BooleanUtils.class.getDeclaredConstructors();
40 final Constructor<?>[] cons = BooleanUtils.class.getDeclaredConstructors();
3741 assertEquals(1, cons.length);
3842 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
3943 assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers()));
134138
135139 @Test
136140 public void test_toBoolean_Integer_Integer_Integer() {
137 Integer six = Integer.valueOf(6);
138 Integer seven = Integer.valueOf(7);
141 final Integer six = Integer.valueOf(6);
142 final Integer seven = Integer.valueOf(7);
139143
140144 assertTrue(BooleanUtils.toBoolean((Integer) null, null, seven));
141145 assertFalse(BooleanUtils.toBoolean((Integer) null, six, null));
169173
170174 @Test
171175 public void test_toBooleanObject_Integer_Integer_Integer_Integer() {
172 Integer six = Integer.valueOf(6);
173 Integer seven = Integer.valueOf(7);
174 Integer eight = Integer.valueOf(8);
176 final Integer six = Integer.valueOf(6);
177 final Integer seven = Integer.valueOf(7);
178 final Integer eight = Integer.valueOf(8);
175179
176180 assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject((Integer) null, null, seven, eight));
177181 assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject((Integer) null, six, null, eight));
228232
229233 @Test
230234 public void test_toIntegerObject_boolean_Integer_Integer() {
231 Integer six = Integer.valueOf(6);
232 Integer seven = Integer.valueOf(7);
235 final Integer six = Integer.valueOf(6);
236 final Integer seven = Integer.valueOf(7);
233237 assertEquals(six, BooleanUtils.toIntegerObject(true, six, seven));
234238 assertEquals(seven, BooleanUtils.toIntegerObject(false, six, seven));
235239 }
236240
237241 @Test
238242 public void test_toIntegerObject_Boolean_Integer_Integer_Integer() {
239 Integer six = Integer.valueOf(6);
240 Integer seven = Integer.valueOf(7);
241 Integer eight = Integer.valueOf(8);
243 final Integer six = Integer.valueOf(6);
244 final Integer seven = Integer.valueOf(7);
245 final Integer eight = Integer.valueOf(8);
242246 assertEquals(six, BooleanUtils.toIntegerObject(Boolean.TRUE, six, seven, eight));
243247 assertEquals(seven, BooleanUtils.toIntegerObject(Boolean.FALSE, six, seven, eight));
244248 assertEquals(eight, BooleanUtils.toIntegerObject((Boolean) null, six, seven, eight));
267271 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
268272 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
269273
270 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("y"));
274 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("y")); // yes
271275 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y"));
272 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("t"));
276 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("t")); // true
273277 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("T"));
274 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("f"));
278 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("f")); // false
275279 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("F"));
276 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("n"));
280 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("n")); // No
277281 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N"));
278282 assertEquals(null, BooleanUtils.toBooleanObject("z"));
279283
441445
442446 @Test
443447 public void testXor_primitive_validInput_2items() {
444 assertTrue(
445 "True result for (true, true)",
446 ! BooleanUtils.xor(new boolean[] { true, true }));
447
448 assertTrue(
449 "True result for (false, false)",
450 ! BooleanUtils.xor(new boolean[] { false, false }));
451
452 assertTrue(
453 "False result for (true, false)",
448 assertEquals(
449 "true ^ true",
450 true ^ true ,
451 BooleanUtils.xor(new boolean[] { true, true }));
452
453 assertEquals(
454 "false ^ false",
455 false ^ false,
456 BooleanUtils.xor(new boolean[] { false, false }));
457
458 assertEquals(
459 "true ^ false",
460 true ^ false,
454461 BooleanUtils.xor(new boolean[] { true, false }));
455462
456 assertTrue(
457 "False result for (false, true)",
463 assertEquals(
464 "false ^ true",
465 false ^ true,
458466 BooleanUtils.xor(new boolean[] { false, true }));
459467 }
460468
461469 @Test
462470 public void testXor_primitive_validInput_3items() {
463 assertTrue(
464 "False result for (false, false, true)",
471 assertEquals(
472 "false ^ false ^ false",
473 false ^ false ^ false,
474 BooleanUtils.xor(new boolean[] { false, false, false }));
475
476 assertEquals(
477 "false ^ false ^ true",
478 false ^ false ^ true,
465479 BooleanUtils.xor(new boolean[] { false, false, true }));
466480
467 assertTrue(
468 "False result for (false, true, false)",
481 assertEquals(
482 "false ^ true ^ false",
483 false ^ true ^ false,
469484 BooleanUtils.xor(new boolean[] { false, true, false }));
470485
471 assertTrue(
472 "False result for (true, false, false)",
486 assertEquals(
487 "false ^ true ^ true",
488 false ^ true ^ true,
489 BooleanUtils.xor(new boolean[] { false, true, true }));
490
491 assertEquals(
492 "true ^ false ^ false",
493 true ^ false ^ false,
473494 BooleanUtils.xor(new boolean[] { true, false, false }));
474495
475 assertTrue(
476 "True result for (true, true, true)",
477 ! BooleanUtils.xor(new boolean[] { true, true, true }));
478
479 assertTrue(
480 "True result for (false, false)",
481 ! BooleanUtils.xor(new boolean[] { false, false, false }));
482
483 assertTrue(
484 "True result for (true, true, false)",
485 ! BooleanUtils.xor(new boolean[] { true, true, false }));
486
487 assertTrue(
488 "True result for (true, false, true)",
489 ! BooleanUtils.xor(new boolean[] { true, false, true }));
490
491 assertTrue(
492 "False result for (false, true, true)",
493 ! BooleanUtils.xor(new boolean[] { false, true, true }));
496 assertEquals(
497 "true ^ false ^ true",
498 true ^ false ^ true,
499 BooleanUtils.xor(new boolean[] { true, false, true }));
500
501 assertEquals(
502 "true ^ true ^ false",
503 true ^ true ^ false,
504 BooleanUtils.xor(new boolean[] { true, true, false }));
505
506 assertEquals(
507 "true ^ true ^ true",
508 true ^ true ^ true,
509 BooleanUtils.xor(new boolean[] { true, true, true }));
494510 }
495511
496512 @Test(expected = IllegalArgumentException.class)
510526
511527 @Test
512528 public void testXor_object_validInput_2items() {
513 assertTrue(
514 "True result for (true, true)",
515 ! BooleanUtils
529 assertEquals(
530 "false ^ false",
531 false ^ false,
532 BooleanUtils
533 .xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
534 .booleanValue());
535
536 assertEquals(
537 "false ^ true",
538 false ^ true,
539 BooleanUtils
540 .xor(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
541 .booleanValue());
542
543 assertEquals(
544 "true ^ false",
545 true ^ false,
546 BooleanUtils
547 .xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
548 .booleanValue());
549
550 assertEquals(
551 "true ^ true",
552 true ^ true,
553 BooleanUtils
516554 .xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
517555 .booleanValue());
518
519 assertTrue(
520 "True result for (false, false)",
521 ! BooleanUtils
522 .xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
523 .booleanValue());
524
525 assertTrue(
526 "False result for (true, false)",
527 BooleanUtils
528 .xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
529 .booleanValue());
530
531 assertTrue(
532 "False result for (false, true)",
533 BooleanUtils
534 .xor(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
535 .booleanValue());
536556 }
537557
538558 @Test
539559 public void testXor_object_validInput_3items() {
540 assertTrue(
541 "False result for (false, false, true)",
560 assertEquals(
561 "false ^ false ^ false",
562 false ^ false ^ false,
563 BooleanUtils.xor(
564 new Boolean[] {
565 Boolean.FALSE,
566 Boolean.FALSE,
567 Boolean.FALSE })
568 .booleanValue());
569
570 assertEquals(
571 "false ^ false ^ true",
572 false ^ false ^ true,
542573 BooleanUtils
543574 .xor(
544575 new Boolean[] {
547578 Boolean.TRUE })
548579 .booleanValue());
549580
550 assertTrue(
551 "False result for (false, true, false)",
581 assertEquals(
582 "false ^ true ^ false",
583 false ^ true ^ false,
552584 BooleanUtils
553585 .xor(
554586 new Boolean[] {
557589 Boolean.FALSE })
558590 .booleanValue());
559591
560 assertTrue(
561 "False result for (true, false, false)",
592 assertEquals(
593 "true ^ false ^ false",
594 true ^ false ^ false,
562595 BooleanUtils
563596 .xor(
564597 new Boolean[] {
567600 Boolean.FALSE })
568601 .booleanValue());
569602
570 assertTrue(
571 "True result for (true, true, true)",
572 ! BooleanUtils
573 .xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
574 .booleanValue());
575
576 assertTrue(
577 "True result for (false, false)",
578 ! BooleanUtils.xor(
579 new Boolean[] {
580 Boolean.FALSE,
581 Boolean.FALSE,
582 Boolean.FALSE })
583 .booleanValue());
584
585 assertTrue(
586 "True result for (true, true, false)",
587 ! BooleanUtils.xor(
603 assertEquals(
604 "true ^ false ^ true",
605 true ^ false ^ true,
606 BooleanUtils.xor(
607 new Boolean[] {
608 Boolean.TRUE,
609 Boolean.FALSE,
610 Boolean.TRUE })
611 .booleanValue());
612
613 assertEquals(
614 "true ^ true ^ false",
615 true ^ true ^ false,
616 BooleanUtils.xor(
588617 new Boolean[] {
589618 Boolean.TRUE,
590619 Boolean.TRUE,
591620 Boolean.FALSE })
592621 .booleanValue());
593622
594 assertTrue(
595 "True result for (true, false, true)",
596 ! BooleanUtils.xor(
597 new Boolean[] {
598 Boolean.TRUE,
599 Boolean.FALSE,
600 Boolean.TRUE })
601 .booleanValue());
602
603 assertTrue(
604 "False result for (false, true, true)",
605 ! BooleanUtils.xor(
623 assertEquals(
624 "false ^ true ^ true",
625 false ^ true ^ true,
626 BooleanUtils.xor(
606627 new Boolean[] {
607628 Boolean.FALSE,
608629 Boolean.TRUE,
609630 Boolean.TRUE })
610631 .booleanValue());
632
633 assertEquals(
634 "true ^ true ^ true",
635 true ^ true ^ true,
636 BooleanUtils
637 .xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
638 .booleanValue());
611639 }
612640
613641 // testAnd
1919 import static org.apache.commons.lang3.JavaVersion.JAVA_1_1;
2020 import static org.apache.commons.lang3.JavaVersion.JAVA_1_2;
2121 import static org.apache.commons.lang3.JavaVersion.JAVA_1_3;
22 import junit.framework.TestCase;
22 import static org.junit.Assert.assertFalse;
23 import static org.junit.Assert.assertTrue;
24
25 import org.junit.Test;
2326
2427 /**
2528 * Tests CharEncoding.
2629 *
2730 * @see CharEncoding
28 * @version $Id: CharEncodingTest.java 1088899 2011-04-05 05:31:27Z bayard $
31 * @version $Id: CharEncodingTest.java 1436768 2013-01-22 07:07:42Z ggregory $
2932 */
30 public class CharEncodingTest extends TestCase {
33 public class CharEncodingTest {
3134
32 private void assertSupportedEncoding(String name) {
35 private void assertSupportedEncoding(final String name) {
3336 assertTrue("Encoding should be supported: " + name, CharEncoding.isSupported(name));
3437 }
3538
3639 /**
3740 * The class can be instantiated.
3841 */
42 @Test
3943 public void testConstructor() {
4044 new CharEncoding();
4145 }
4246
47 @Test
4348 public void testMustBeSupportedJava1_3_1() {
4449 if (SystemUtils.isJavaVersionAtLeast(JAVA_1_3)) {
4550 this.assertSupportedEncoding(CharEncoding.ISO_8859_1);
5358 }
5459 }
5560
61 @Test
5662 public void testSupported() {
5763 assertTrue(CharEncoding.isSupported("UTF8"));
5864 assertTrue(CharEncoding.isSupported("UTF-8"));
5965 assertTrue(CharEncoding.isSupported("ASCII"));
6066 }
6167
68 @Test
6269 public void testNotSupported() {
6370 assertFalse(CharEncoding.isSupported(null));
6471 assertFalse(CharEncoding.isSupported(""));
6875 assertFalse(CharEncoding.isSupported("this is not a valid encoding name"));
6976 }
7077
78 @Test
7179 public void testWorksOnJava1_1_8() {
7280 //
7381 // In this test, I simply deleted the encodings from the 1.3.1 list.
8290 }
8391 }
8492
93 @Test
8594 public void testWorksOnJava1_2_2() {
8695 //
8796 // In this test, I simply deleted the encodings from the 1.3.1 list.
96105 }
97106 }
98107
99 void warn(String msg) {
108 void warn(final String msg) {
100109 System.err.println(msg);
101110 }
102111 }
1717 */
1818 package org.apache.commons.lang3;
1919
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertNotNull;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
2026 import java.lang.reflect.Modifier;
2127 import java.util.Iterator;
2228 import java.util.NoSuchElementException;
2329
24 import junit.framework.TestCase;
30 import org.junit.Test;
2531
2632 /**
2733 * Unit tests {@link org.apache.commons.lang3.CharRange}.
2834 *
29 * @version $Id: CharRangeTest.java 1090427 2011-04-08 20:17:10Z bayard $
35 * @version $Id: CharRangeTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3036 */
31 public class CharRangeTest extends TestCase {
32
33 public CharRangeTest(String name) {
34 super(name);
35 }
36
37 //-----------------------------------------------------------------------
37 public class CharRangeTest {
38
39 //-----------------------------------------------------------------------
40 @Test
3841 public void testClass() {
3942 // class changed to non-public in 3.0
40 assertEquals(false, Modifier.isPublic(CharRange.class.getModifiers()));
41 assertEquals(true, Modifier.isFinal(CharRange.class.getModifiers()));
42 }
43
44 //-----------------------------------------------------------------------
43 assertFalse(Modifier.isPublic(CharRange.class.getModifiers()));
44 assertTrue(Modifier.isFinal(CharRange.class.getModifiers()));
45 }
46
47 //-----------------------------------------------------------------------
48 @Test
4549 public void testConstructorAccessors_is() {
46 CharRange rangea = CharRange.is('a');
50 final CharRange rangea = CharRange.is('a');
4751 assertEquals('a', rangea.getStart());
4852 assertEquals('a', rangea.getEnd());
49 assertEquals(false, rangea.isNegated());
53 assertFalse(rangea.isNegated());
5054 assertEquals("a", rangea.toString());
5155 }
5256
57 @Test
5358 public void testConstructorAccessors_isNot() {
54 CharRange rangea = CharRange.isNot('a');
59 final CharRange rangea = CharRange.isNot('a');
5560 assertEquals('a', rangea.getStart());
5661 assertEquals('a', rangea.getEnd());
57 assertEquals(true, rangea.isNegated());
62 assertTrue(rangea.isNegated());
5863 assertEquals("^a", rangea.toString());
5964 }
6065
66 @Test
6167 public void testConstructorAccessors_isIn_Same() {
62 CharRange rangea = CharRange.isIn('a', 'a');
68 final CharRange rangea = CharRange.isIn('a', 'a');
6369 assertEquals('a', rangea.getStart());
6470 assertEquals('a', rangea.getEnd());
65 assertEquals(false, rangea.isNegated());
71 assertFalse(rangea.isNegated());
6672 assertEquals("a", rangea.toString());
6773 }
6874
75 @Test
6976 public void testConstructorAccessors_isIn_Normal() {
70 CharRange rangea = CharRange.isIn('a', 'e');
77 final CharRange rangea = CharRange.isIn('a', 'e');
7178 assertEquals('a', rangea.getStart());
7279 assertEquals('e', rangea.getEnd());
73 assertEquals(false, rangea.isNegated());
80 assertFalse(rangea.isNegated());
7481 assertEquals("a-e", rangea.toString());
7582 }
7683
84 @Test
7785 public void testConstructorAccessors_isIn_Reversed() {
78 CharRange rangea = CharRange.isIn('e', 'a');
86 final CharRange rangea = CharRange.isIn('e', 'a');
7987 assertEquals('a', rangea.getStart());
8088 assertEquals('e', rangea.getEnd());
81 assertEquals(false, rangea.isNegated());
89 assertFalse(rangea.isNegated());
8290 assertEquals("a-e", rangea.toString());
8391 }
8492
93 @Test
8594 public void testConstructorAccessors_isNotIn_Same() {
86 CharRange rangea = CharRange.isNotIn('a', 'a');
95 final CharRange rangea = CharRange.isNotIn('a', 'a');
8796 assertEquals('a', rangea.getStart());
8897 assertEquals('a', rangea.getEnd());
89 assertEquals(true, rangea.isNegated());
98 assertTrue(rangea.isNegated());
9099 assertEquals("^a", rangea.toString());
91100 }
92101
102 @Test
93103 public void testConstructorAccessors_isNotIn_Normal() {
94 CharRange rangea = CharRange.isNotIn('a', 'e');
104 final CharRange rangea = CharRange.isNotIn('a', 'e');
95105 assertEquals('a', rangea.getStart());
96106 assertEquals('e', rangea.getEnd());
97 assertEquals(true, rangea.isNegated());
107 assertTrue(rangea.isNegated());
98108 assertEquals("^a-e", rangea.toString());
99109 }
100110
111 @Test
101112 public void testConstructorAccessors_isNotIn_Reversed() {
102 CharRange rangea = CharRange.isNotIn('e', 'a');
113 final CharRange rangea = CharRange.isNotIn('e', 'a');
103114 assertEquals('a', rangea.getStart());
104115 assertEquals('e', rangea.getEnd());
105 assertEquals(true, rangea.isNegated());
116 assertTrue(rangea.isNegated());
106117 assertEquals("^a-e", rangea.toString());
107118 }
108119
109120 //-----------------------------------------------------------------------
121 @Test
110122 public void testEquals_Object() {
111 CharRange rangea = CharRange.is('a');
112 CharRange rangeae = CharRange.isIn('a', 'e');
113 CharRange rangenotbf = CharRange.isIn('b', 'f');
114
115 assertEquals(false, rangea.equals(null));
116
117 assertEquals(true, rangea.equals(rangea));
118 assertEquals(true, rangea.equals(CharRange.is('a')));
119 assertEquals(true, rangeae.equals(rangeae));
120 assertEquals(true, rangeae.equals(CharRange.isIn('a', 'e')));
121 assertEquals(true, rangenotbf.equals(rangenotbf));
122 assertEquals(true, rangenotbf.equals(CharRange.isIn('b', 'f')));
123
124 assertEquals(false, rangea.equals(rangeae));
125 assertEquals(false, rangea.equals(rangenotbf));
126 assertEquals(false, rangeae.equals(rangea));
127 assertEquals(false, rangeae.equals(rangenotbf));
128 assertEquals(false, rangenotbf.equals(rangea));
129 assertEquals(false, rangenotbf.equals(rangeae));
130 }
131
123 final CharRange rangea = CharRange.is('a');
124 final CharRange rangeae = CharRange.isIn('a', 'e');
125 final CharRange rangenotbf = CharRange.isIn('b', 'f');
126
127 assertFalse(rangea.equals(null));
128
129 assertTrue(rangea.equals(rangea));
130 assertTrue(rangea.equals(CharRange.is('a')));
131 assertTrue(rangeae.equals(rangeae));
132 assertTrue(rangeae.equals(CharRange.isIn('a', 'e')));
133 assertTrue(rangenotbf.equals(rangenotbf));
134 assertTrue(rangenotbf.equals(CharRange.isIn('b', 'f')));
135
136 assertFalse(rangea.equals(rangeae));
137 assertFalse(rangea.equals(rangenotbf));
138 assertFalse(rangeae.equals(rangea));
139 assertFalse(rangeae.equals(rangenotbf));
140 assertFalse(rangenotbf.equals(rangea));
141 assertFalse(rangenotbf.equals(rangeae));
142 }
143
144 @Test
132145 public void testHashCode() {
133 CharRange rangea = CharRange.is('a');
134 CharRange rangeae = CharRange.isIn('a', 'e');
135 CharRange rangenotbf = CharRange.isIn('b', 'f');
136
137 assertEquals(true, rangea.hashCode() == rangea.hashCode());
138 assertEquals(true, rangea.hashCode() == CharRange.is('a').hashCode());
139 assertEquals(true, rangeae.hashCode() == rangeae.hashCode());
140 assertEquals(true, rangeae.hashCode() == CharRange.isIn('a', 'e').hashCode());
141 assertEquals(true, rangenotbf.hashCode() == rangenotbf.hashCode());
142 assertEquals(true, rangenotbf.hashCode() == CharRange.isIn('b', 'f').hashCode());
143
144 assertEquals(false, rangea.hashCode() == rangeae.hashCode());
145 assertEquals(false, rangea.hashCode() == rangenotbf.hashCode());
146 assertEquals(false, rangeae.hashCode() == rangea.hashCode());
147 assertEquals(false, rangeae.hashCode() == rangenotbf.hashCode());
148 assertEquals(false, rangenotbf.hashCode() == rangea.hashCode());
149 assertEquals(false, rangenotbf.hashCode() == rangeae.hashCode());
150 }
151
152 //-----------------------------------------------------------------------
146 final CharRange rangea = CharRange.is('a');
147 final CharRange rangeae = CharRange.isIn('a', 'e');
148 final CharRange rangenotbf = CharRange.isIn('b', 'f');
149
150 assertTrue(rangea.hashCode() == rangea.hashCode());
151 assertTrue(rangea.hashCode() == CharRange.is('a').hashCode());
152 assertTrue(rangeae.hashCode() == rangeae.hashCode());
153 assertTrue(rangeae.hashCode() == CharRange.isIn('a', 'e').hashCode());
154 assertTrue(rangenotbf.hashCode() == rangenotbf.hashCode());
155 assertTrue(rangenotbf.hashCode() == CharRange.isIn('b', 'f').hashCode());
156
157 assertFalse(rangea.hashCode() == rangeae.hashCode());
158 assertFalse(rangea.hashCode() == rangenotbf.hashCode());
159 assertFalse(rangeae.hashCode() == rangea.hashCode());
160 assertFalse(rangeae.hashCode() == rangenotbf.hashCode());
161 assertFalse(rangenotbf.hashCode() == rangea.hashCode());
162 assertFalse(rangenotbf.hashCode() == rangeae.hashCode());
163 }
164
165 //-----------------------------------------------------------------------
166 @Test
153167 public void testContains_Char() {
154168 CharRange range = CharRange.is('c');
155 assertEquals(false, range.contains('b'));
156 assertEquals(true, range.contains('c'));
157 assertEquals(false, range.contains('d'));
158 assertEquals(false, range.contains('e'));
169 assertFalse(range.contains('b'));
170 assertTrue(range.contains('c'));
171 assertFalse(range.contains('d'));
172 assertFalse(range.contains('e'));
159173
160174 range = CharRange.isIn('c', 'd');
161 assertEquals(false, range.contains('b'));
162 assertEquals(true, range.contains('c'));
163 assertEquals(true, range.contains('d'));
164 assertEquals(false, range.contains('e'));
175 assertFalse(range.contains('b'));
176 assertTrue(range.contains('c'));
177 assertTrue(range.contains('d'));
178 assertFalse(range.contains('e'));
165179
166180 range = CharRange.isIn('d', 'c');
167 assertEquals(false, range.contains('b'));
168 assertEquals(true, range.contains('c'));
169 assertEquals(true, range.contains('d'));
170 assertEquals(false, range.contains('e'));
181 assertFalse(range.contains('b'));
182 assertTrue(range.contains('c'));
183 assertTrue(range.contains('d'));
184 assertFalse(range.contains('e'));
171185
172186 range = CharRange.isNotIn('c', 'd');
173 assertEquals(true, range.contains('b'));
174 assertEquals(false, range.contains('c'));
175 assertEquals(false, range.contains('d'));
176 assertEquals(true, range.contains('e'));
177 assertEquals(true, range.contains((char) 0));
178 assertEquals(true, range.contains(Character.MAX_VALUE));
179 }
180
181 //-----------------------------------------------------------------------
187 assertTrue(range.contains('b'));
188 assertFalse(range.contains('c'));
189 assertFalse(range.contains('d'));
190 assertTrue(range.contains('e'));
191 assertTrue(range.contains((char) 0));
192 assertTrue(range.contains(Character.MAX_VALUE));
193 }
194
195 //-----------------------------------------------------------------------
196 @Test
182197 public void testContains_Charrange() {
183 CharRange a = CharRange.is('a');
184 CharRange b = CharRange.is('b');
185 CharRange c = CharRange.is('c');
186 CharRange c2 = CharRange.is('c');
187 CharRange d = CharRange.is('d');
188 CharRange e = CharRange.is('e');
189 CharRange cd = CharRange.isIn('c', 'd');
190 CharRange bd = CharRange.isIn('b', 'd');
191 CharRange bc = CharRange.isIn('b', 'c');
192 CharRange ab = CharRange.isIn('a', 'b');
193 CharRange de = CharRange.isIn('d', 'e');
194 CharRange ef = CharRange.isIn('e', 'f');
195 CharRange ae = CharRange.isIn('a', 'e');
198 final CharRange a = CharRange.is('a');
199 final CharRange b = CharRange.is('b');
200 final CharRange c = CharRange.is('c');
201 final CharRange c2 = CharRange.is('c');
202 final CharRange d = CharRange.is('d');
203 final CharRange e = CharRange.is('e');
204 final CharRange cd = CharRange.isIn('c', 'd');
205 final CharRange bd = CharRange.isIn('b', 'd');
206 final CharRange bc = CharRange.isIn('b', 'c');
207 final CharRange ab = CharRange.isIn('a', 'b');
208 final CharRange de = CharRange.isIn('d', 'e');
209 final CharRange ef = CharRange.isIn('e', 'f');
210 final CharRange ae = CharRange.isIn('a', 'e');
196211
197212 // normal/normal
198 assertEquals(false, c.contains(b));
199 assertEquals(true, c.contains(c));
200 assertEquals(true, c.contains(c2));
201 assertEquals(false, c.contains(d));
202
203 assertEquals(false, c.contains(cd));
204 assertEquals(false, c.contains(bd));
205 assertEquals(false, c.contains(bc));
206 assertEquals(false, c.contains(ab));
207 assertEquals(false, c.contains(de));
208
209 assertEquals(true, cd.contains(c));
210 assertEquals(true, bd.contains(c));
211 assertEquals(true, bc.contains(c));
212 assertEquals(false, ab.contains(c));
213 assertEquals(false, de.contains(c));
214
215 assertEquals(true, ae.contains(b));
216 assertEquals(true, ae.contains(ab));
217 assertEquals(true, ae.contains(bc));
218 assertEquals(true, ae.contains(cd));
219 assertEquals(true, ae.contains(de));
220
221 CharRange notb = CharRange.isNot('b');
222 CharRange notc = CharRange.isNot('c');
223 CharRange notd = CharRange.isNot('d');
224 CharRange notab = CharRange.isNotIn('a', 'b');
225 CharRange notbc = CharRange.isNotIn('b', 'c');
226 CharRange notbd = CharRange.isNotIn('b', 'd');
227 CharRange notcd = CharRange.isNotIn('c', 'd');
228 CharRange notde = CharRange.isNotIn('d', 'e');
229 CharRange notae = CharRange.isNotIn('a', 'e');
230 CharRange all = CharRange.isIn((char) 0, Character.MAX_VALUE);
231 CharRange allbutfirst = CharRange.isIn((char) 1, Character.MAX_VALUE);
213 assertFalse(c.contains(b));
214 assertTrue(c.contains(c));
215 assertTrue(c.contains(c2));
216 assertFalse(c.contains(d));
217
218 assertFalse(c.contains(cd));
219 assertFalse(c.contains(bd));
220 assertFalse(c.contains(bc));
221 assertFalse(c.contains(ab));
222 assertFalse(c.contains(de));
223
224 assertTrue(cd.contains(c));
225 assertTrue(bd.contains(c));
226 assertTrue(bc.contains(c));
227 assertFalse(ab.contains(c));
228 assertFalse(de.contains(c));
229
230 assertTrue(ae.contains(b));
231 assertTrue(ae.contains(ab));
232 assertTrue(ae.contains(bc));
233 assertTrue(ae.contains(cd));
234 assertTrue(ae.contains(de));
235
236 final CharRange notb = CharRange.isNot('b');
237 final CharRange notc = CharRange.isNot('c');
238 final CharRange notd = CharRange.isNot('d');
239 final CharRange notab = CharRange.isNotIn('a', 'b');
240 final CharRange notbc = CharRange.isNotIn('b', 'c');
241 final CharRange notbd = CharRange.isNotIn('b', 'd');
242 final CharRange notcd = CharRange.isNotIn('c', 'd');
243 final CharRange notde = CharRange.isNotIn('d', 'e');
244 final CharRange notae = CharRange.isNotIn('a', 'e');
245 final CharRange all = CharRange.isIn((char) 0, Character.MAX_VALUE);
246 final CharRange allbutfirst = CharRange.isIn((char) 1, Character.MAX_VALUE);
232247
233248 // normal/negated
234 assertEquals(false, c.contains(notc));
235 assertEquals(false, c.contains(notbd));
236 assertEquals(true, all.contains(notc));
237 assertEquals(true, all.contains(notbd));
238 assertEquals(false, allbutfirst.contains(notc));
239 assertEquals(false, allbutfirst.contains(notbd));
249 assertFalse(c.contains(notc));
250 assertFalse(c.contains(notbd));
251 assertTrue(all.contains(notc));
252 assertTrue(all.contains(notbd));
253 assertFalse(allbutfirst.contains(notc));
254 assertFalse(allbutfirst.contains(notbd));
240255
241256 // negated/normal
242 assertEquals(true, notc.contains(a));
243 assertEquals(true, notc.contains(b));
244 assertEquals(false, notc.contains(c));
245 assertEquals(true, notc.contains(d));
246 assertEquals(true, notc.contains(e));
247
248 assertEquals(true, notc.contains(ab));
249 assertEquals(false, notc.contains(bc));
250 assertEquals(false, notc.contains(bd));
251 assertEquals(false, notc.contains(cd));
252 assertEquals(true, notc.contains(de));
253 assertEquals(false, notc.contains(ae));
254 assertEquals(false, notc.contains(all));
255 assertEquals(false, notc.contains(allbutfirst));
256
257 assertEquals(true, notbd.contains(a));
258 assertEquals(false, notbd.contains(b));
259 assertEquals(false, notbd.contains(c));
260 assertEquals(false, notbd.contains(d));
261 assertEquals(true, notbd.contains(e));
262
263 assertEquals(true, notcd.contains(ab));
264 assertEquals(false, notcd.contains(bc));
265 assertEquals(false, notcd.contains(bd));
266 assertEquals(false, notcd.contains(cd));
267 assertEquals(false, notcd.contains(de));
268 assertEquals(false, notcd.contains(ae));
269 assertEquals(true, notcd.contains(ef));
270 assertEquals(false, notcd.contains(all));
271 assertEquals(false, notcd.contains(allbutfirst));
257 assertTrue(notc.contains(a));
258 assertTrue(notc.contains(b));
259 assertFalse(notc.contains(c));
260 assertTrue(notc.contains(d));
261 assertTrue(notc.contains(e));
262
263 assertTrue(notc.contains(ab));
264 assertFalse(notc.contains(bc));
265 assertFalse(notc.contains(bd));
266 assertFalse(notc.contains(cd));
267 assertTrue(notc.contains(de));
268 assertFalse(notc.contains(ae));
269 assertFalse(notc.contains(all));
270 assertFalse(notc.contains(allbutfirst));
271
272 assertTrue(notbd.contains(a));
273 assertFalse(notbd.contains(b));
274 assertFalse(notbd.contains(c));
275 assertFalse(notbd.contains(d));
276 assertTrue(notbd.contains(e));
277
278 assertTrue(notcd.contains(ab));
279 assertFalse(notcd.contains(bc));
280 assertFalse(notcd.contains(bd));
281 assertFalse(notcd.contains(cd));
282 assertFalse(notcd.contains(de));
283 assertFalse(notcd.contains(ae));
284 assertTrue(notcd.contains(ef));
285 assertFalse(notcd.contains(all));
286 assertFalse(notcd.contains(allbutfirst));
272287
273288 // negated/negated
274 assertEquals(false, notc.contains(notb));
275 assertEquals(true, notc.contains(notc));
276 assertEquals(false, notc.contains(notd));
277
278 assertEquals(false, notc.contains(notab));
279 assertEquals(true, notc.contains(notbc));
280 assertEquals(true, notc.contains(notbd));
281 assertEquals(true, notc.contains(notcd));
282 assertEquals(false, notc.contains(notde));
283
284 assertEquals(false, notbd.contains(notb));
285 assertEquals(false, notbd.contains(notc));
286 assertEquals(false, notbd.contains(notd));
287
288 assertEquals(false, notbd.contains(notab));
289 assertEquals(false, notbd.contains(notbc));
290 assertEquals(true, notbd.contains(notbd));
291 assertEquals(false, notbd.contains(notcd));
292 assertEquals(false, notbd.contains(notde));
293 assertEquals(true, notbd.contains(notae));
294 }
295
289 assertFalse(notc.contains(notb));
290 assertTrue(notc.contains(notc));
291 assertFalse(notc.contains(notd));
292
293 assertFalse(notc.contains(notab));
294 assertTrue(notc.contains(notbc));
295 assertTrue(notc.contains(notbd));
296 assertTrue(notc.contains(notcd));
297 assertFalse(notc.contains(notde));
298
299 assertFalse(notbd.contains(notb));
300 assertFalse(notbd.contains(notc));
301 assertFalse(notbd.contains(notd));
302
303 assertFalse(notbd.contains(notab));
304 assertFalse(notbd.contains(notbc));
305 assertTrue(notbd.contains(notbd));
306 assertFalse(notbd.contains(notcd));
307 assertFalse(notbd.contains(notde));
308 assertTrue(notbd.contains(notae));
309 }
310
311 @Test
296312 public void testContainsNullArg() {
297 CharRange range = CharRange.is('a');
313 final CharRange range = CharRange.is('a');
298314 try {
299315 @SuppressWarnings("unused")
316 final
300317 boolean contains = range.contains(null);
301 } catch(IllegalArgumentException e) {
318 } catch(final IllegalArgumentException e) {
302319 assertEquals("The Range must not be null", e.getMessage());
303320 }
304321 }
305322
323 @Test
306324 public void testIterator() {
307 CharRange a = CharRange.is('a');
308 CharRange ad = CharRange.isIn('a', 'd');
309 CharRange nota = CharRange.isNot('a');
310 CharRange emptySet = CharRange.isNotIn((char) 0, Character.MAX_VALUE);
311 CharRange notFirst = CharRange.isNotIn((char) 1, Character.MAX_VALUE);
312 CharRange notLast = CharRange.isNotIn((char) 0, (char) (Character.MAX_VALUE - 1));
313
314 Iterator<Character> aIt = a.iterator();
325 final CharRange a = CharRange.is('a');
326 final CharRange ad = CharRange.isIn('a', 'd');
327 final CharRange nota = CharRange.isNot('a');
328 final CharRange emptySet = CharRange.isNotIn((char) 0, Character.MAX_VALUE);
329 final CharRange notFirst = CharRange.isNotIn((char) 1, Character.MAX_VALUE);
330 final CharRange notLast = CharRange.isNotIn((char) 0, (char) (Character.MAX_VALUE - 1));
331
332 final Iterator<Character> aIt = a.iterator();
315333 assertNotNull(aIt);
316334 assertTrue(aIt.hasNext());
317335 assertEquals(Character.valueOf('a'), aIt.next());
318336 assertFalse(aIt.hasNext());
319337
320 Iterator<Character> adIt = ad.iterator();
338 final Iterator<Character> adIt = ad.iterator();
321339 assertNotNull(adIt);
322340 assertTrue(adIt.hasNext());
323341 assertEquals(Character.valueOf('a'), adIt.next());
326344 assertEquals(Character.valueOf('d'), adIt.next());
327345 assertFalse(adIt.hasNext());
328346
329 Iterator<Character> notaIt = nota.iterator();
347 final Iterator<Character> notaIt = nota.iterator();
330348 assertNotNull(notaIt);
331349 assertTrue(notaIt.hasNext());
332350 while (notaIt.hasNext()) {
333 Character c = notaIt.next();
351 final Character c = notaIt.next();
334352 assertFalse('a' == c.charValue());
335353 }
336354
337 Iterator<Character> emptySetIt = emptySet.iterator();
355 final Iterator<Character> emptySetIt = emptySet.iterator();
338356 assertNotNull(emptySetIt);
339357 assertFalse(emptySetIt.hasNext());
340358 try {
341359 emptySetIt.next();
342360 fail("Should throw NoSuchElementException");
343 } catch (NoSuchElementException e) {
361 } catch (final NoSuchElementException e) {
344362 assertTrue(true);
345363 }
346364
347 Iterator<Character> notFirstIt = notFirst.iterator();
365 final Iterator<Character> notFirstIt = notFirst.iterator();
348366 assertNotNull(notFirstIt);
349367 assertTrue(notFirstIt.hasNext());
350368 assertEquals(Character.valueOf((char) 0), notFirstIt.next());
352370 try {
353371 notFirstIt.next();
354372 fail("Should throw NoSuchElementException");
355 } catch (NoSuchElementException e) {
373 } catch (final NoSuchElementException e) {
356374 assertTrue(true);
357375 }
358376
359 Iterator<Character> notLastIt = notLast.iterator();
377 final Iterator<Character> notLastIt = notLast.iterator();
360378 assertNotNull(notLastIt);
361379 assertTrue(notLastIt.hasNext());
362380 assertEquals(Character.valueOf(Character.MAX_VALUE), notLastIt.next());
364382 try {
365383 notLastIt.next();
366384 fail("Should throw NoSuchElementException");
367 } catch (NoSuchElementException e) {
385 } catch (final NoSuchElementException e) {
368386 assertTrue(true);
369387 }
370388 }
371389
372390 //-----------------------------------------------------------------------
391 @Test
373392 public void testSerialization() {
374393 CharRange range = CharRange.is('a');
375394 assertEquals(range, SerializationUtils.clone(range));
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertTrue;
22
1823 import java.lang.reflect.Constructor;
1924 import java.lang.reflect.Modifier;
2025
21 import junit.framework.Assert;
22 import junit.framework.TestCase;
26 import org.junit.Assert;
27
28 import org.junit.Test;
2329
2430 /**
2531 * Tests CharSequenceUtils
2632 *
2733 * @version $Id: CharSequenceUtilsTest.java 1066341 2011-02-02 06:21:53Z bayard $
2834 */
29 public class CharSequenceUtilsTest extends TestCase {
35 public class CharSequenceUtilsTest {
3036
3137 //-----------------------------------------------------------------------
38 @Test
3239 public void testConstructor() {
3340 assertNotNull(new CharSequenceUtils());
34 Constructor<?>[] cons = CharSequenceUtils.class.getDeclaredConstructors();
41 final Constructor<?>[] cons = CharSequenceUtils.class.getDeclaredConstructors();
3542 assertEquals(1, cons.length);
36 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
37 assertEquals(true, Modifier.isPublic(CharSequenceUtils.class.getModifiers()));
38 assertEquals(false, Modifier.isFinal(CharSequenceUtils.class.getModifiers()));
43 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
44 assertTrue(Modifier.isPublic(CharSequenceUtils.class.getModifiers()));
45 assertFalse(Modifier.isFinal(CharSequenceUtils.class.getModifiers()));
3946 }
4047
4148 //-----------------------------------------------------------------------
49 @Test
4250 public void testSubSequence() {
4351 //
4452 // null input
6068 try {
6169 Assert.assertEquals(null, CharSequenceUtils.subSequence(StringUtils.EMPTY, -1));
6270 Assert.fail("Expected " + IndexOutOfBoundsException.class.getName());
63 } catch (IndexOutOfBoundsException e) {
71 } catch (final IndexOutOfBoundsException e) {
6472 // Expected
6573 }
6674 try {
6775 Assert.assertEquals(null, CharSequenceUtils.subSequence(StringUtils.EMPTY, 1));
6876 Assert.fail("Expected " + IndexOutOfBoundsException.class.getName());
69 } catch (IndexOutOfBoundsException e) {
77 } catch (final IndexOutOfBoundsException e) {
7078 // Expected
7179 }
7280 }
1717 */
1818 package org.apache.commons.lang3;
1919
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertSame;
23 import static org.junit.Assert.assertTrue;
24
2025 import java.lang.reflect.Modifier;
2126
22 import junit.framework.TestCase;
27 import org.junit.Test;
2328
2429 /**
2530 * Unit tests {@link org.apache.commons.lang3.CharSet}.
2631 *
27 * @version $Id: CharSetTest.java 1088899 2011-04-05 05:31:27Z bayard $
32 * @version $Id: CharSetTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2833 */
29 public class CharSetTest extends TestCase {
30
31 public CharSetTest(String name) {
32 super(name);
33 }
34 public class CharSetTest {
3435
3536 //-----------------------------------------------------------------------
37 @Test
3638 public void testClass() {
37 assertEquals(true, Modifier.isPublic(CharSet.class.getModifiers()));
38 assertEquals(false, Modifier.isFinal(CharSet.class.getModifiers()));
39 assertTrue(Modifier.isPublic(CharSet.class.getModifiers()));
40 assertFalse(Modifier.isFinal(CharSet.class.getModifiers()));
3941 }
4042
4143 //-----------------------------------------------------------------------
44 @Test
4245 public void testGetInstance() {
4346 assertSame(CharSet.EMPTY, CharSet.getInstance( (String) null));
4447 assertSame(CharSet.EMPTY, CharSet.getInstance(""));
5053 }
5154
5255 //-----------------------------------------------------------------------
56 @Test
5357 public void testGetInstance_Stringarray() {
5458 assertEquals(null, CharSet.getInstance((String[]) null));
5559 assertEquals("[]", CharSet.getInstance(new String[0]).toString());
5862 }
5963
6064 //-----------------------------------------------------------------------
65 @Test
6166 public void testConstructor_String_simple() {
6267 CharSet set;
6368 CharRange[] array;
97102 assertEquals("^a-e", array[0].toString());
98103 }
99104
105 @Test
100106 public void testConstructor_String_combo() {
101107 CharSet set;
102108 CharRange[] array;
104110 set = CharSet.getInstance("abc");
105111 array = set.getCharRanges();
106112 assertEquals(3, array.length);
107 assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
108 assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
109 assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
113 assertTrue(ArrayUtils.contains(array, CharRange.is('a')));
114 assertTrue(ArrayUtils.contains(array, CharRange.is('b')));
115 assertTrue(ArrayUtils.contains(array, CharRange.is('c')));
110116
111117 set = CharSet.getInstance("a-ce-f");
112118 array = set.getCharRanges();
113119 assertEquals(2, array.length);
114 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'c')));
115 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
120 assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', 'c')));
121 assertTrue(ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
116122
117123 set = CharSet.getInstance("ae-f");
118124 array = set.getCharRanges();
119125 assertEquals(2, array.length);
120 assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
121 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
126 assertTrue(ArrayUtils.contains(array, CharRange.is('a')));
127 assertTrue(ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
122128
123129 set = CharSet.getInstance("e-fa");
124130 array = set.getCharRanges();
125131 assertEquals(2, array.length);
126 assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
127 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
132 assertTrue(ArrayUtils.contains(array, CharRange.is('a')));
133 assertTrue(ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
128134
129135 set = CharSet.getInstance("ae-fm-pz");
130136 array = set.getCharRanges();
131137 assertEquals(4, array.length);
132 assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
133 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
134 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('m', 'p')));
135 assertEquals(true, ArrayUtils.contains(array, CharRange.is('z')));
136 }
137
138 assertTrue(ArrayUtils.contains(array, CharRange.is('a')));
139 assertTrue(ArrayUtils.contains(array, CharRange.isIn('e', 'f')));
140 assertTrue(ArrayUtils.contains(array, CharRange.isIn('m', 'p')));
141 assertTrue(ArrayUtils.contains(array, CharRange.is('z')));
142 }
143
144 @Test
138145 public void testConstructor_String_comboNegated() {
139146 CharSet set;
140147 CharRange[] array;
142149 set = CharSet.getInstance("^abc");
143150 array = set.getCharRanges();
144151 assertEquals(3, array.length);
145 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
146 assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
147 assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
152 assertTrue(ArrayUtils.contains(array, CharRange.isNot('a')));
153 assertTrue(ArrayUtils.contains(array, CharRange.is('b')));
154 assertTrue(ArrayUtils.contains(array, CharRange.is('c')));
148155
149156 set = CharSet.getInstance("b^ac");
150157 array = set.getCharRanges();
151158 assertEquals(3, array.length);
152 assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
153 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
154 assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
159 assertTrue(ArrayUtils.contains(array, CharRange.is('b')));
160 assertTrue(ArrayUtils.contains(array, CharRange.isNot('a')));
161 assertTrue(ArrayUtils.contains(array, CharRange.is('c')));
155162
156163 set = CharSet.getInstance("db^ac");
157164 array = set.getCharRanges();
158165 assertEquals(4, array.length);
159 assertEquals(true, ArrayUtils.contains(array, CharRange.is('d')));
160 assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
161 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
162 assertEquals(true, ArrayUtils.contains(array, CharRange.is('c')));
166 assertTrue(ArrayUtils.contains(array, CharRange.is('d')));
167 assertTrue(ArrayUtils.contains(array, CharRange.is('b')));
168 assertTrue(ArrayUtils.contains(array, CharRange.isNot('a')));
169 assertTrue(ArrayUtils.contains(array, CharRange.is('c')));
163170
164171 set = CharSet.getInstance("^b^a");
165172 array = set.getCharRanges();
166173 assertEquals(2, array.length);
167 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('b')));
168 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a')));
174 assertTrue(ArrayUtils.contains(array, CharRange.isNot('b')));
175 assertTrue(ArrayUtils.contains(array, CharRange.isNot('a')));
169176
170177 set = CharSet.getInstance("b^a-c^z");
171178 array = set.getCharRanges();
172179 assertEquals(3, array.length);
173 assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('a', 'c')));
174 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('z')));
175 assertEquals(true, ArrayUtils.contains(array, CharRange.is('b')));
176 }
177
180 assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('a', 'c')));
181 assertTrue(ArrayUtils.contains(array, CharRange.isNot('z')));
182 assertTrue(ArrayUtils.contains(array, CharRange.is('b')));
183 }
184
185 @Test
178186 public void testConstructor_String_oddDash() {
179187 CharSet set;
180188 CharRange[] array;
182190 set = CharSet.getInstance("-");
183191 array = set.getCharRanges();
184192 assertEquals(1, array.length);
185 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
193 assertTrue(ArrayUtils.contains(array, CharRange.is('-')));
186194
187195 set = CharSet.getInstance("--");
188196 array = set.getCharRanges();
189197 assertEquals(1, array.length);
190 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
198 assertTrue(ArrayUtils.contains(array, CharRange.is('-')));
191199
192200 set = CharSet.getInstance("---");
193201 array = set.getCharRanges();
194202 assertEquals(1, array.length);
195 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
203 assertTrue(ArrayUtils.contains(array, CharRange.is('-')));
196204
197205 set = CharSet.getInstance("----");
198206 array = set.getCharRanges();
199207 assertEquals(1, array.length);
200 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
208 assertTrue(ArrayUtils.contains(array, CharRange.is('-')));
201209
202210 set = CharSet.getInstance("-a");
203211 array = set.getCharRanges();
204212 assertEquals(2, array.length);
205 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
206 assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
213 assertTrue(ArrayUtils.contains(array, CharRange.is('-')));
214 assertTrue(ArrayUtils.contains(array, CharRange.is('a')));
207215
208216 set = CharSet.getInstance("a-");
209217 array = set.getCharRanges();
210218 assertEquals(2, array.length);
211 assertEquals(true, ArrayUtils.contains(array, CharRange.is('a')));
212 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-')));
219 assertTrue(ArrayUtils.contains(array, CharRange.is('a')));
220 assertTrue(ArrayUtils.contains(array, CharRange.is('-')));
213221
214222 set = CharSet.getInstance("a--");
215223 array = set.getCharRanges();
216224 assertEquals(1, array.length);
217 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', '-')));
225 assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', '-')));
218226
219227 set = CharSet.getInstance("--a");
220228 array = set.getCharRanges();
221229 assertEquals(1, array.length);
222 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('-', 'a')));
223 }
224
230 assertTrue(ArrayUtils.contains(array, CharRange.isIn('-', 'a')));
231 }
232
233 @Test
225234 public void testConstructor_String_oddNegate() {
226235 CharSet set;
227236 CharRange[] array;
228237 set = CharSet.getInstance("^");
229238 array = set.getCharRanges();
230239 assertEquals(1, array.length);
231 assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^"
240 assertTrue(ArrayUtils.contains(array, CharRange.is('^'))); // "^"
232241
233242 set = CharSet.getInstance("^^");
234243 array = set.getCharRanges();
235244 assertEquals(1, array.length);
236 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
245 assertTrue(ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
237246
238247 set = CharSet.getInstance("^^^");
239248 array = set.getCharRanges();
240249 assertEquals(2, array.length);
241 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
242 assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^"
250 assertTrue(ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
251 assertTrue(ArrayUtils.contains(array, CharRange.is('^'))); // "^"
243252
244253 set = CharSet.getInstance("^^^^");
245254 array = set.getCharRanges();
246255 assertEquals(1, array.length);
247 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^" x2
256 assertTrue(ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^" x2
248257
249258 set = CharSet.getInstance("a^");
250259 array = set.getCharRanges();
251260 assertEquals(2, array.length);
252 assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); // "a"
253 assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^"
261 assertTrue(ArrayUtils.contains(array, CharRange.is('a'))); // "a"
262 assertTrue(ArrayUtils.contains(array, CharRange.is('^'))); // "^"
254263
255264 set = CharSet.getInstance("^a-");
256265 array = set.getCharRanges();
257266 assertEquals(2, array.length);
258 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a'))); // "^a"
259 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); // "-"
267 assertTrue(ArrayUtils.contains(array, CharRange.isNot('a'))); // "^a"
268 assertTrue(ArrayUtils.contains(array, CharRange.is('-'))); // "-"
260269
261270 set = CharSet.getInstance("^^-c");
262271 array = set.getCharRanges();
263272 assertEquals(1, array.length);
264 assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('^', 'c'))); // "^^-c"
273 assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('^', 'c'))); // "^^-c"
265274
266275 set = CharSet.getInstance("^c-^");
267276 array = set.getCharRanges();
268277 assertEquals(1, array.length);
269 assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^"
278 assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^"
270279
271280 set = CharSet.getInstance("^c-^d");
272281 array = set.getCharRanges();
273282 assertEquals(2, array.length);
274 assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^"
275 assertEquals(true, ArrayUtils.contains(array, CharRange.is('d'))); // "d"
283 assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^"
284 assertTrue(ArrayUtils.contains(array, CharRange.is('d'))); // "d"
276285
277286 set = CharSet.getInstance("^^-");
278287 array = set.getCharRanges();
279288 assertEquals(2, array.length);
280 assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
281 assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); // "-"
282 }
283
289 assertTrue(ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^"
290 assertTrue(ArrayUtils.contains(array, CharRange.is('-'))); // "-"
291 }
292
293 @Test
284294 public void testConstructor_String_oddCombinations() {
285295 CharSet set;
286296 CharRange[] array = null;
287297
288298 set = CharSet.getInstance("a-^c");
289299 array = set.getCharRanges();
290 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', '^'))); // "a-^"
291 assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); // "c"
292 assertEquals(false, set.contains('b'));
293 assertEquals(true, set.contains('^'));
294 assertEquals(true, set.contains('_')); // between ^ and a
295 assertEquals(true, set.contains('c'));
300 assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', '^'))); // "a-^"
301 assertTrue(ArrayUtils.contains(array, CharRange.is('c'))); // "c"
302 assertFalse(set.contains('b'));
303 assertTrue(set.contains('^'));
304 assertTrue(set.contains('_')); // between ^ and a
305 assertTrue(set.contains('c'));
296306
297307 set = CharSet.getInstance("^a-^c");
298308 array = set.getCharRanges();
299 assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('a', '^'))); // "^a-^"
300 assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); // "c"
301 assertEquals(true, set.contains('b'));
302 assertEquals(false, set.contains('^'));
303 assertEquals(false, set.contains('_')); // between ^ and a
309 assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('a', '^'))); // "^a-^"
310 assertTrue(ArrayUtils.contains(array, CharRange.is('c'))); // "c"
311 assertTrue(set.contains('b'));
312 assertFalse(set.contains('^'));
313 assertFalse(set.contains('_')); // between ^ and a
304314
305315 set = CharSet.getInstance("a- ^-- "); //contains everything
306316 array = set.getCharRanges();
307 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', ' '))); // "a- "
308 assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('-', ' '))); // "^-- "
309 assertEquals(true, set.contains('#'));
310 assertEquals(true, set.contains('^'));
311 assertEquals(true, set.contains('a'));
312 assertEquals(true, set.contains('*'));
313 assertEquals(true, set.contains('A'));
317 assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', ' '))); // "a- "
318 assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('-', ' '))); // "^-- "
319 assertTrue(set.contains('#'));
320 assertTrue(set.contains('^'));
321 assertTrue(set.contains('a'));
322 assertTrue(set.contains('*'));
323 assertTrue(set.contains('A'));
314324
315325 set = CharSet.getInstance("^-b");
316326 array = set.getCharRanges();
317 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "^-b"
318 assertEquals(true, set.contains('b'));
319 assertEquals(true, set.contains('_')); // between ^ and a
320 assertEquals(false, set.contains('A'));
321 assertEquals(true, set.contains('^'));
327 assertTrue(ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "^-b"
328 assertTrue(set.contains('b'));
329 assertTrue(set.contains('_')); // between ^ and a
330 assertFalse(set.contains('A'));
331 assertTrue(set.contains('^'));
322332
323333 set = CharSet.getInstance("b-^");
324334 array = set.getCharRanges();
325 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "b-^"
326 assertEquals(true, set.contains('b'));
327 assertEquals(true, set.contains('^'));
328 assertEquals(true, set.contains('a')); // between ^ and b
329 assertEquals(false, set.contains('c'));
335 assertTrue(ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "b-^"
336 assertTrue(set.contains('b'));
337 assertTrue(set.contains('^'));
338 assertTrue(set.contains('a')); // between ^ and b
339 assertFalse(set.contains('c'));
330340 }
331341
332342 //-----------------------------------------------------------------------
343 @Test
333344 public void testEquals_Object() {
334 CharSet abc = CharSet.getInstance("abc");
335 CharSet abc2 = CharSet.getInstance("abc");
336 CharSet atoc = CharSet.getInstance("a-c");
337 CharSet atoc2 = CharSet.getInstance("a-c");
338 CharSet notatoc = CharSet.getInstance("^a-c");
339 CharSet notatoc2 = CharSet.getInstance("^a-c");
340
341 assertEquals(false, abc.equals(null));
342
343 assertEquals(true, abc.equals(abc));
344 assertEquals(true, abc.equals(abc2));
345 assertEquals(false, abc.equals(atoc));
346 assertEquals(false, abc.equals(notatoc));
347
348 assertEquals(false, atoc.equals(abc));
349 assertEquals(true, atoc.equals(atoc));
350 assertEquals(true, atoc.equals(atoc2));
351 assertEquals(false, atoc.equals(notatoc));
352
353 assertEquals(false, notatoc.equals(abc));
354 assertEquals(false, notatoc.equals(atoc));
355 assertEquals(true, notatoc.equals(notatoc));
356 assertEquals(true, notatoc.equals(notatoc2));
345 final CharSet abc = CharSet.getInstance("abc");
346 final CharSet abc2 = CharSet.getInstance("abc");
347 final CharSet atoc = CharSet.getInstance("a-c");
348 final CharSet atoc2 = CharSet.getInstance("a-c");
349 final CharSet notatoc = CharSet.getInstance("^a-c");
350 final CharSet notatoc2 = CharSet.getInstance("^a-c");
351
352 assertFalse(abc.equals(null));
353
354 assertTrue(abc.equals(abc));
355 assertTrue(abc.equals(abc2));
356 assertFalse(abc.equals(atoc));
357 assertFalse(abc.equals(notatoc));
358
359 assertFalse(atoc.equals(abc));
360 assertTrue(atoc.equals(atoc));
361 assertTrue(atoc.equals(atoc2));
362 assertFalse(atoc.equals(notatoc));
363
364 assertFalse(notatoc.equals(abc));
365 assertFalse(notatoc.equals(atoc));
366 assertTrue(notatoc.equals(notatoc));
367 assertTrue(notatoc.equals(notatoc2));
357368 }
358369
370 @Test
359371 public void testHashCode() {
360 CharSet abc = CharSet.getInstance("abc");
361 CharSet abc2 = CharSet.getInstance("abc");
362 CharSet atoc = CharSet.getInstance("a-c");
363 CharSet atoc2 = CharSet.getInstance("a-c");
364 CharSet notatoc = CharSet.getInstance("^a-c");
365 CharSet notatoc2 = CharSet.getInstance("^a-c");
372 final CharSet abc = CharSet.getInstance("abc");
373 final CharSet abc2 = CharSet.getInstance("abc");
374 final CharSet atoc = CharSet.getInstance("a-c");
375 final CharSet atoc2 = CharSet.getInstance("a-c");
376 final CharSet notatoc = CharSet.getInstance("^a-c");
377 final CharSet notatoc2 = CharSet.getInstance("^a-c");
366378
367379 assertEquals(abc.hashCode(), abc.hashCode());
368380 assertEquals(abc.hashCode(), abc2.hashCode());
373385 }
374386
375387 //-----------------------------------------------------------------------
388 @Test
376389 public void testContains_Char() {
377 CharSet btod = CharSet.getInstance("b-d");
378 CharSet dtob = CharSet.getInstance("d-b");
379 CharSet bcd = CharSet.getInstance("bcd");
380 CharSet bd = CharSet.getInstance("bd");
381 CharSet notbtod = CharSet.getInstance("^b-d");
382
383 assertEquals(false, btod.contains('a'));
384 assertEquals(true, btod.contains('b'));
385 assertEquals(true, btod.contains('c'));
386 assertEquals(true, btod.contains('d'));
387 assertEquals(false, btod.contains('e'));
388
389 assertEquals(false, bcd.contains('a'));
390 assertEquals(true, bcd.contains('b'));
391 assertEquals(true, bcd.contains('c'));
392 assertEquals(true, bcd.contains('d'));
393 assertEquals(false, bcd.contains('e'));
394
395 assertEquals(false, bd.contains('a'));
396 assertEquals(true, bd.contains('b'));
397 assertEquals(false, bd.contains('c'));
398 assertEquals(true, bd.contains('d'));
399 assertEquals(false, bd.contains('e'));
400
401 assertEquals(true, notbtod.contains('a'));
402 assertEquals(false, notbtod.contains('b'));
403 assertEquals(false, notbtod.contains('c'));
404 assertEquals(false, notbtod.contains('d'));
405 assertEquals(true, notbtod.contains('e'));
406
407 assertEquals(false, dtob.contains('a'));
408 assertEquals(true, dtob.contains('b'));
409 assertEquals(true, dtob.contains('c'));
410 assertEquals(true, dtob.contains('d'));
411 assertEquals(false, dtob.contains('e'));
390 final CharSet btod = CharSet.getInstance("b-d");
391 final CharSet dtob = CharSet.getInstance("d-b");
392 final CharSet bcd = CharSet.getInstance("bcd");
393 final CharSet bd = CharSet.getInstance("bd");
394 final CharSet notbtod = CharSet.getInstance("^b-d");
395
396 assertFalse(btod.contains('a'));
397 assertTrue(btod.contains('b'));
398 assertTrue(btod.contains('c'));
399 assertTrue(btod.contains('d'));
400 assertFalse(btod.contains('e'));
401
402 assertFalse(bcd.contains('a'));
403 assertTrue(bcd.contains('b'));
404 assertTrue(bcd.contains('c'));
405 assertTrue(bcd.contains('d'));
406 assertFalse(bcd.contains('e'));
407
408 assertFalse(bd.contains('a'));
409 assertTrue(bd.contains('b'));
410 assertFalse(bd.contains('c'));
411 assertTrue(bd.contains('d'));
412 assertFalse(bd.contains('e'));
413
414 assertTrue(notbtod.contains('a'));
415 assertFalse(notbtod.contains('b'));
416 assertFalse(notbtod.contains('c'));
417 assertFalse(notbtod.contains('d'));
418 assertTrue(notbtod.contains('e'));
419
420 assertFalse(dtob.contains('a'));
421 assertTrue(dtob.contains('b'));
422 assertTrue(dtob.contains('c'));
423 assertTrue(dtob.contains('d'));
424 assertFalse(dtob.contains('e'));
412425
413 CharRange[] array = dtob.getCharRanges();
426 final CharRange[] array = dtob.getCharRanges();
414427 assertEquals("[b-d]", dtob.toString());
415428 assertEquals(1, array.length);
416429 }
417430
418431 //-----------------------------------------------------------------------
432 @Test
419433 public void testSerialization() {
420434 CharSet set = CharSet.getInstance("a");
421435 assertEquals(set, SerializationUtils.clone(set));
426440 }
427441
428442 //-----------------------------------------------------------------------
443 @Test
429444 public void testStatics() {
430445 CharRange[] array;
431446
434449
435450 array = CharSet.ASCII_ALPHA.getCharRanges();
436451 assertEquals(2, array.length);
437 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'z')));
438 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('A', 'Z')));
452 assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', 'z')));
453 assertTrue(ArrayUtils.contains(array, CharRange.isIn('A', 'Z')));
439454
440455 array = CharSet.ASCII_ALPHA_LOWER.getCharRanges();
441456 assertEquals(1, array.length);
442 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'z')));
457 assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', 'z')));
443458
444459 array = CharSet.ASCII_ALPHA_UPPER.getCharRanges();
445460 assertEquals(1, array.length);
446 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('A', 'Z')));
461 assertTrue(ArrayUtils.contains(array, CharRange.isIn('A', 'Z')));
447462
448463 array = CharSet.ASCII_NUMERIC.getCharRanges();
449464 assertEquals(1, array.length);
450 assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('0', '9')));
465 assertTrue(ArrayUtils.contains(array, CharRange.isIn('0', '9')));
451466 }
452467
453468 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertTrue;
22
1823 import java.lang.reflect.Constructor;
1924 import java.lang.reflect.Modifier;
2025
21 import junit.framework.TestCase;
26 import org.junit.Test;
2227
2328 /**
2429 * Unit tests {@link org.apache.commons.lang3.CharSetUtils}.
2530 *
26 * @version $Id: CharSetUtilsTest.java 1088899 2011-04-05 05:31:27Z bayard $
31 * @version $Id: CharSetUtilsTest.java 1470130 2013-04-20 09:05:43Z bayard $
2732 */
28 public class CharSetUtilsTest extends TestCase {
29
30 public CharSetUtilsTest(String name) {
31 super(name);
32 }
33
34 //-----------------------------------------------------------------------
33 public class CharSetUtilsTest {
34
35 //-----------------------------------------------------------------------
36 @Test
3537 public void testConstructor() {
3638 assertNotNull(new CharSetUtils());
37 Constructor<?>[] cons = CharSetUtils.class.getDeclaredConstructors();
39 final Constructor<?>[] cons = CharSetUtils.class.getDeclaredConstructors();
3840 assertEquals(1, cons.length);
39 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
40 assertEquals(true, Modifier.isPublic(CharSetUtils.class.getModifiers()));
41 assertEquals(false, Modifier.isFinal(CharSetUtils.class.getModifiers()));
42 }
43
44 //-----------------------------------------------------------------------
41 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
42 assertTrue(Modifier.isPublic(CharSetUtils.class.getModifiers()));
43 assertFalse(Modifier.isFinal(CharSetUtils.class.getModifiers()));
44 }
45
46 //-----------------------------------------------------------------------
47 @Test
4548 public void testSqueeze_StringString() {
4649 assertEquals(null, CharSetUtils.squeeze(null, (String) null));
4750 assertEquals(null, CharSetUtils.squeeze(null, ""));
5861 assertEquals("hello", CharSetUtils.squeeze("helloo", "^l"));
5962 }
6063
64 @Test
6165 public void testSqueeze_StringStringarray() {
6266 assertEquals(null, CharSetUtils.squeeze(null, (String[]) null));
6367 assertEquals(null, CharSetUtils.squeeze(null, new String[0]));
8185 }
8286
8387 //-----------------------------------------------------------------------
88 @Test
89 public void testContainsAny_StringString() {
90 assertFalse(CharSetUtils.containsAny(null, (String) null));
91 assertFalse(CharSetUtils.containsAny(null, ""));
92
93 assertFalse(CharSetUtils.containsAny("", (String) null));
94 assertFalse(CharSetUtils.containsAny("", ""));
95 assertFalse(CharSetUtils.containsAny("", "a-e"));
96
97 assertFalse(CharSetUtils.containsAny("hello", (String) null));
98 assertFalse(CharSetUtils.containsAny("hello", ""));
99 assertTrue(CharSetUtils.containsAny("hello", "a-e"));
100 assertTrue(CharSetUtils.containsAny("hello", "l-p"));
101 }
102
103 @Test
104 public void testContainsAny_StringStringarray() {
105 assertFalse(CharSetUtils.containsAny(null, (String[]) null));
106 assertFalse(CharSetUtils.containsAny(null, new String[0]));
107 assertFalse(CharSetUtils.containsAny(null, new String[] {null}));
108 assertFalse(CharSetUtils.containsAny(null, new String[] {"a-e"}));
109
110 assertFalse(CharSetUtils.containsAny("", (String[]) null));
111 assertFalse(CharSetUtils.containsAny("", new String[0]));
112 assertFalse(CharSetUtils.containsAny("", new String[] {null}));
113 assertFalse(CharSetUtils.containsAny("", new String[] {"a-e"}));
114
115 assertFalse(CharSetUtils.containsAny("hello", (String[]) null));
116 assertFalse(CharSetUtils.containsAny("hello", new String[0]));
117 assertFalse(CharSetUtils.containsAny("hello", new String[] {null}));
118 assertTrue(CharSetUtils.containsAny("hello", new String[] {"a-e"}));
119
120 assertTrue(CharSetUtils.containsAny("hello", new String[] { "el" }));
121 assertFalse(CharSetUtils.containsAny("hello", new String[] { "x" }));
122 assertTrue(CharSetUtils.containsAny("hello", new String[] { "e-i" }));
123 assertTrue(CharSetUtils.containsAny("hello", new String[] { "a-z" }));
124 assertFalse(CharSetUtils.containsAny("hello", new String[] { "" }));
125 }
126
127 //-----------------------------------------------------------------------
128 @Test
84129 public void testCount_StringString() {
85130 assertEquals(0, CharSetUtils.count(null, (String) null));
86131 assertEquals(0, CharSetUtils.count(null, ""));
95140 assertEquals(3, CharSetUtils.count("hello", "l-p"));
96141 }
97142
143 @Test
98144 public void testCount_StringStringarray() {
99145 assertEquals(0, CharSetUtils.count(null, (String[]) null));
100146 assertEquals(0, CharSetUtils.count(null, new String[0]));
119165 }
120166
121167 //-----------------------------------------------------------------------
168 @Test
122169 public void testKeep_StringString() {
123170 assertEquals(null, CharSetUtils.keep(null, (String) null));
124171 assertEquals(null, CharSetUtils.keep(null, ""));
135182 assertEquals("ell", CharSetUtils.keep("hello", "el"));
136183 }
137184
185 @Test
138186 public void testKeep_StringStringarray() {
139187 assertEquals(null, CharSetUtils.keep(null, (String[]) null));
140188 assertEquals(null, CharSetUtils.keep(null, new String[0]));
160208 }
161209
162210 //-----------------------------------------------------------------------
211 @Test
163212 public void testDelete_StringString() {
164213 assertEquals(null, CharSetUtils.delete(null, (String) null));
165214 assertEquals(null, CharSetUtils.delete(null, ""));
175224 assertEquals("hello", CharSetUtils.delete("hello", "z"));
176225 }
177226
227 @Test
178228 public void testDelete_StringStringarray() {
179229 assertEquals(null, CharSetUtils.delete(null, (String[]) null));
180230 assertEquals(null, CharSetUtils.delete(null, new String[0]));
5353 run_inlined_CharUtils_isAsciiNumeric: 84,420 milliseconds.
5454
5555
56 * @version $Id: CharUtilsPerfRun.java 1199894 2011-11-09 17:53:59Z ggregory $
56 * @version $Id: CharUtilsPerfRun.java 1436770 2013-01-22 07:09:45Z ggregory $
5757 */
5858 public class CharUtilsPerfRun {
59 final static String VERSION = "$Id: CharUtilsPerfRun.java 1199894 2011-11-09 17:53:59Z ggregory $";
59 final static String VERSION = "$Id: CharUtilsPerfRun.java 1436770 2013-01-22 07:09:45Z ggregory $";
6060
6161 final static int WARM_UP = 100;
6262
7070 }
7171 }
7272
73 public static void main(String[] args) {
73 public static void main(final String[] args) {
7474 new CharUtilsPerfRun().run();
7575 }
7676
121121 this.printlnTotal("run_CharSet", start);
122122 }
123123
124 private int run_CharSet(int loopCount) {
124 private int run_CharSet(final int loopCount) {
125125 int t = 0;
126126 for (int i = 0; i < loopCount; i++) {
127 for (char ch : CHAR_SAMPLES) {
128 boolean b = CharSet.ASCII_NUMERIC.contains(ch);
127 for (final char ch : CHAR_SAMPLES) {
128 final boolean b = CharSet.ASCII_NUMERIC.contains(ch);
129129 t += b ? 1 : 0;
130130 }
131131 }
132132 return t;
133133 }
134134
135 private int run_CharUtils_isAsciiNumeric(int loopCount) {
135 private int run_CharUtils_isAsciiNumeric(final int loopCount) {
136136 int t = 0;
137137 for (int i = 0; i < loopCount; i++) {
138 for (char ch : CHAR_SAMPLES) {
139 boolean b = CharUtils.isAsciiNumeric(ch);
138 for (final char ch : CHAR_SAMPLES) {
139 final boolean b = CharUtils.isAsciiNumeric(ch);
140140 t += b ? 1 : 0;
141141 }
142142 }
143143 return t;
144144 }
145145
146 private int run_inlined_CharUtils_isAsciiNumeric(int loopCount) {
146 private int run_inlined_CharUtils_isAsciiNumeric(final int loopCount) {
147147 int t = 0;
148148 for (int i = 0; i < loopCount; i++) {
149 for (char ch : CHAR_SAMPLES) {
150 boolean b = ch >= '0' && ch <= '9';
149 for (final char ch : CHAR_SAMPLES) {
150 final boolean b = ch >= '0' && ch <= '9';
151151 t += b ? 1 : 0;
152152 }
153153 }
154154 return t;
155155 }
156156
157 private void printlnTotal(String prefix, long start) {
158 long total = System.currentTimeMillis() - start;
157 private void printlnTotal(final String prefix, final long start) {
158 final long total = System.currentTimeMillis() - start;
159159 System.out.println(prefix + ": " + NumberFormat.getInstance().format(total) + " milliseconds.");
160160 }
161161 }
2929 /**
3030 * Unit tests {@link org.apache.commons.lang3.CharUtils}.
3131 *
32 * @version $Id: CharUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
32 * @version $Id: CharUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3333 */
3434 public class CharUtilsTest {
3535
4040 @Test
4141 public void testConstructor() {
4242 assertNotNull(new CharUtils());
43 Constructor<?>[] cons = CharUtils.class.getDeclaredConstructors();
43 final Constructor<?>[] cons = CharUtils.class.getDeclaredConstructors();
4444 assertEquals(1, cons.length);
4545 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
4646 assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers()));
4747 assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers()));
4848 }
4949
50 @SuppressWarnings("deprecation") // intentional test of deprecated method
5051 @Test
5152 public void testToCharacterObject_char() {
5253 assertEquals(new Character('a'), CharUtils.toCharacterObject('a'));
5354 assertSame(CharUtils.toCharacterObject('a'), CharUtils.toCharacterObject('a'));
5455
5556 for (int i = 0; i < 128; i++) {
56 Character ch = CharUtils.toCharacterObject((char) i);
57 Character ch2 = CharUtils.toCharacterObject((char) i);
57 final Character ch = CharUtils.toCharacterObject((char) i);
58 final Character ch2 = CharUtils.toCharacterObject((char) i);
5859 assertSame(ch, ch2);
5960 assertEquals(i, ch.charValue());
6061 }
6162 for (int i = 128; i < 196; i++) {
62 Character ch = CharUtils.toCharacterObject((char) i);
63 Character ch2 = CharUtils.toCharacterObject((char) i);
63 final Character ch = CharUtils.toCharacterObject((char) i);
64 final Character ch2 = CharUtils.toCharacterObject((char) i);
6465 assertEquals(ch, ch2);
6566 assertTrue(ch != ch2);
6667 assertEquals(i, ch.charValue());
6768 assertEquals(i, ch2.charValue());
6869 }
70 assertSame(CharUtils.toCharacterObject("a"), CharUtils.toCharacterObject('a'));
6971 }
7072
7173 @Test
7577 assertEquals(new Character('a'), CharUtils.toCharacterObject("a"));
7678 assertEquals(new Character('a'), CharUtils.toCharacterObject("abc"));
7779 assertSame(CharUtils.toCharacterObject("a"), CharUtils.toCharacterObject("a"));
78 assertSame(CharUtils.toCharacterObject("a"), CharUtils.toCharacterObject('a'));
7980 }
8081
8182 @Test
8485 assertEquals('B', CharUtils.toChar(CHARACTER_B));
8586 try {
8687 CharUtils.toChar((Character) null);
87 } catch (IllegalArgumentException ex) {}
88 } catch (final IllegalArgumentException ex) {}
8889 }
8990
9091 @Test
100101 assertEquals('B', CharUtils.toChar("BA"));
101102 try {
102103 CharUtils.toChar((String) null);
103 } catch (IllegalArgumentException ex) {}
104 } catch (final IllegalArgumentException ex) {}
104105 try {
105106 CharUtils.toChar("");
106 } catch (IllegalArgumentException ex) {}
107 } catch (final IllegalArgumentException ex) {}
107108 }
108109
109110 @Test
128129 assertEquals(9, CharUtils.toIntValue('9'));
129130 try {
130131 CharUtils.toIntValue('a');
131 } catch (IllegalArgumentException ex) {}
132 } catch (final IllegalArgumentException ex) {}
132133 }
133134
134135 @Test
144145 assertEquals(3, CharUtils.toIntValue(new Character('3')));
145146 try {
146147 CharUtils.toIntValue(null);
147 } catch (IllegalArgumentException ex) {}
148 } catch (final IllegalArgumentException ex) {}
148149 try {
149150 CharUtils.toIntValue(CHARACTER_A);
150 } catch (IllegalArgumentException ex) {}
151 } catch (final IllegalArgumentException ex) {}
151152 }
152153
153154 @Test
164165 assertSame(CharUtils.toString('a'), CharUtils.toString('a'));
165166
166167 for (int i = 0; i < 128; i++) {
167 String str = CharUtils.toString((char) i);
168 String str2 = CharUtils.toString((char) i);
168 final String str = CharUtils.toString((char) i);
169 final String str2 = CharUtils.toString((char) i);
169170 assertSame(str, str2);
170171 assertEquals(1, str.length());
171172 assertEquals(i, str.charAt(0));
172173 }
173174 for (int i = 128; i < 196; i++) {
174 String str = CharUtils.toString((char) i);
175 String str2 = CharUtils.toString((char) i);
175 final String str = CharUtils.toString((char) i);
176 final String str2 = CharUtils.toString((char) i);
176177 assertEquals(str, str2);
177178 assertTrue(str != str2);
178179 assertEquals(1, str.length());
194195 assertEquals("\\u0041", CharUtils.unicodeEscaped('A'));
195196
196197 for (int i = 0; i < 196; i++) {
197 String str = CharUtils.unicodeEscaped((char) i);
198 final String str = CharUtils.unicodeEscaped((char) i);
198199 assertEquals(6, str.length());
199 int val = Integer.parseInt(str.substring(2), 16);
200 final int val = Integer.parseInt(str.substring(2), 16);
200201 assertEquals(i, val);
201202 }
202203 assertEquals("\\u0999", CharUtils.unicodeEscaped((char) 0x999));
1616 package org.apache.commons.lang3;
1717
1818 import static org.apache.commons.lang3.JavaVersion.JAVA_1_5;
19 import static org.junit.Assert.assertArrayEquals;
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertNotNull;
23 import static org.junit.Assert.assertNotSame;
24 import static org.junit.Assert.assertNull;
25 import static org.junit.Assert.assertSame;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
1928
2029 import java.lang.reflect.Constructor;
2130 import java.lang.reflect.Method;
2433 import java.util.Arrays;
2534 import java.util.Collections;
2635 import java.util.HashSet;
36 import java.util.Iterator;
2737 import java.util.List;
2838 import java.util.Map;
2939 import java.util.Set;
3040
31 import junit.framework.TestCase;
41 import org.apache.commons.lang3.ClassUtils.Interfaces;
42 import org.apache.commons.lang3.reflect.testbed.GenericConsumer;
43 import org.apache.commons.lang3.reflect.testbed.GenericParent;
44 import org.apache.commons.lang3.reflect.testbed.StringParameterizedChild;
45 import org.junit.Test;
3246
3347 /**
3448 * Unit tests {@link org.apache.commons.lang3.ClassUtils}.
3549 *
36 * @version $Id: ClassUtilsTest.java 1199730 2011-11-09 13:00:47Z sebb $
50 * @version $Id: ClassUtilsTest.java 1510298 2013-08-04 18:36:17Z mbenson $
3751 */
38 public class ClassUtilsTest extends TestCase {
39
40 public ClassUtilsTest(String name) {
41 super(name);
42 }
52 @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long
53 public class ClassUtilsTest {
4354
4455 private static class Inner {
4556 private class DeeplyNested{}
4657 }
4758
4859 //-----------------------------------------------------------------------
60 @Test
4961 public void testConstructor() {
5062 assertNotNull(new ClassUtils());
51 Constructor<?>[] cons = ClassUtils.class.getDeclaredConstructors();
63 final Constructor<?>[] cons = ClassUtils.class.getDeclaredConstructors();
5264 assertEquals(1, cons.length);
53 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
54 assertEquals(true, Modifier.isPublic(ClassUtils.class.getModifiers()));
55 assertEquals(false, Modifier.isFinal(ClassUtils.class.getModifiers()));
65 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
66 assertTrue(Modifier.isPublic(ClassUtils.class.getModifiers()));
67 assertFalse(Modifier.isFinal(ClassUtils.class.getModifiers()));
5668 }
5769
5870 // -------------------------------------------------------------------------
71 @Test
5972 public void test_getShortClassName_Object() {
6073 assertEquals("ClassUtils", ClassUtils.getShortClassName(new ClassUtils(), "<null>"));
6174 assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortClassName(new Inner(), "<null>"));
6982 assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortClassName(new Inner(), "<null>"));
7083 }
7184
85 @Test
7286 public void test_getShortClassName_Class() {
7387 assertEquals("ClassUtils", ClassUtils.getShortClassName(ClassUtils.class));
7488 assertEquals("Map.Entry", ClassUtils.getShortClassName(Map.Entry.class));
112126
113127
114128
129 @Test
115130 public void test_getShortClassName_String() {
116131 assertEquals("ClassUtils", ClassUtils.getShortClassName(ClassUtils.class.getName()));
117132 assertEquals("Map.Entry", ClassUtils.getShortClassName(Map.Entry.class.getName()));
119134 assertEquals("", ClassUtils.getShortClassName(""));
120135 }
121136
137 @Test
122138 public void test_getSimpleName_Class() {
123139 assertEquals("ClassUtils", ClassUtils.getSimpleName(ClassUtils.class));
124140 assertEquals("Entry", ClassUtils.getSimpleName(Map.Entry.class));
159175 assertEquals("Named", ClassUtils.getSimpleName(Named.class));
160176 }
161177
178 @Test
162179 public void test_getSimpleName_Object() {
163180 assertEquals("ClassUtils", ClassUtils.getSimpleName(new ClassUtils(), "<null>"));
164181 assertEquals("Inner", ClassUtils.getSimpleName(new Inner(), "<null>"));
167184 }
168185
169186 // -------------------------------------------------------------------------
187 @Test
170188 public void test_getPackageName_Object() {
171189 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new ClassUtils(), "<null>"));
172190 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new Inner(), "<null>"));
173191 assertEquals("<null>", ClassUtils.getPackageName(null, "<null>"));
174192 }
175193
194 @Test
176195 public void test_getPackageName_Class() {
177196 assertEquals("java.lang", ClassUtils.getPackageName(String.class));
178197 assertEquals("java.util", ClassUtils.getPackageName(Map.Entry.class));
202221 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(Named.class));
203222 }
204223
224 @Test
205225 public void test_getPackageName_String() {
206226 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(ClassUtils.class.getName()));
207227 assertEquals("java.util", ClassUtils.getPackageName(Map.Entry.class.getName()));
210230 }
211231
212232 // -------------------------------------------------------------------------
233 @Test
213234 public void test_getAllSuperclasses_Class() {
214 List<?> list = ClassUtils.getAllSuperclasses(CY.class);
235 final List<?> list = ClassUtils.getAllSuperclasses(CY.class);
215236 assertEquals(2, list.size());
216237 assertEquals(CX.class, list.get(0));
217238 assertEquals(Object.class, list.get(1));
219240 assertEquals(null, ClassUtils.getAllSuperclasses(null));
220241 }
221242
243 @Test
222244 public void test_getAllInterfaces_Class() {
223 List<?> list = ClassUtils.getAllInterfaces(CY.class);
245 final List<?> list = ClassUtils.getAllInterfaces(CY.class);
224246 assertEquals(6, list.size());
225247 assertEquals(IB.class, list.get(0));
226248 assertEquals(IC.class, list.get(1));
250272 }
251273
252274 // -------------------------------------------------------------------------
275 @Test
253276 public void test_convertClassNamesToClasses_List() {
254 List<String> list = new ArrayList<String>();
277 final List<String> list = new ArrayList<String>();
255278 List<Class<?>> result = ClassUtils.convertClassNamesToClasses(list);
256279 assertEquals(0, result.size());
257280
265288 assertEquals(Object.class, result.get(2));
266289
267290 @SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
291 final
268292 List<Object> olist = (List<Object>)(List<?>)list;
269293 olist.add(new Object());
270294 try {
271295 ClassUtils.convertClassNamesToClasses(list);
272296 fail("Should not have been able to convert list");
273 } catch (ClassCastException expected) {}
297 } catch (final ClassCastException expected) {}
274298 assertEquals(null, ClassUtils.convertClassNamesToClasses(null));
275299 }
276300
301 @Test
277302 public void test_convertClassesToClassNames_List() {
278 List<Class<?>> list = new ArrayList<Class<?>>();
303 final List<Class<?>> list = new ArrayList<Class<?>>();
279304 List<String> result = ClassUtils.convertClassesToClassNames(list);
280305 assertEquals(0, result.size());
281306
289314 assertEquals("java.lang.Object", result.get(2));
290315
291316 @SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
317 final
292318 List<Object> olist = (List<Object>)(List<?>)list;
293319 olist.add(new Object());
294320 try {
295321 ClassUtils.convertClassesToClassNames(list);
296322 fail("Should not have been able to convert list");
297 } catch (ClassCastException expected) {}
323 } catch (final ClassCastException expected) {}
298324 assertEquals(null, ClassUtils.convertClassesToClassNames(null));
299325 }
300326
301327 // -------------------------------------------------------------------------
328 @Test
302329 public void test_isInnerClass_Class() {
303 assertEquals(true, ClassUtils.isInnerClass(Inner.class));
304 assertEquals(true, ClassUtils.isInnerClass(Map.Entry.class));
305 assertEquals(true, ClassUtils.isInnerClass(new Cloneable() {
330 assertTrue(ClassUtils.isInnerClass(Inner.class));
331 assertTrue(ClassUtils.isInnerClass(Map.Entry.class));
332 assertTrue(ClassUtils.isInnerClass(new Cloneable() {
306333 }.getClass()));
307 assertEquals(false, ClassUtils.isInnerClass(this.getClass()));
308 assertEquals(false, ClassUtils.isInnerClass(String.class));
309 assertEquals(false, ClassUtils.isInnerClass(null));
334 assertFalse(ClassUtils.isInnerClass(this.getClass()));
335 assertFalse(ClassUtils.isInnerClass(String.class));
336 assertFalse(ClassUtils.isInnerClass(null));
310337 }
311338
312339 // -------------------------------------------------------------------------
340 @Test
313341 public void test_isAssignable_ClassArray_ClassArray() throws Exception {
314 Class<?>[] array2 = new Class[] {Object.class, Object.class};
315 Class<?>[] array1 = new Class[] {Object.class};
316 Class<?>[] array1s = new Class[] {String.class};
317 Class<?>[] array0 = new Class[] {};
318 Class<?>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
319 Class<?>[] arrayWrappers = { Integer.class, Boolean.class };
342 final Class<?>[] array2 = new Class[] {Object.class, Object.class};
343 final Class<?>[] array1 = new Class[] {Object.class};
344 final Class<?>[] array1s = new Class[] {String.class};
345 final Class<?>[] array0 = new Class[] {};
346 final Class<?>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
347 final Class<?>[] arrayWrappers = { Integer.class, Boolean.class };
320348
321349 assertFalse(ClassUtils.isAssignable(array1, array2));
322350 assertFalse(ClassUtils.isAssignable(null, array2));
330358 assertTrue(ClassUtils.isAssignable(array1s, array1s));
331359 assertTrue(ClassUtils.isAssignable(array1s, array1));
332360
333 boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
361 final boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
334362
335363 assertEquals(autoboxing, ClassUtils.isAssignable(arrayPrimitives, arrayWrappers));
336364 assertEquals(autoboxing, ClassUtils.isAssignable(arrayWrappers, arrayPrimitives));
340368 assertTrue(ClassUtils.isAssignable(arrayWrappers, array2));
341369 }
342370
371 @Test
343372 public void test_isAssignable_ClassArray_ClassArray_Autoboxing() throws Exception {
344 Class<?>[] array2 = new Class[] {Object.class, Object.class};
345 Class<?>[] array1 = new Class[] {Object.class};
346 Class<?>[] array1s = new Class[] {String.class};
347 Class<?>[] array0 = new Class[] {};
348 Class<?>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
349 Class<?>[] arrayWrappers = { Integer.class, Boolean.class };
373 final Class<?>[] array2 = new Class[] {Object.class, Object.class};
374 final Class<?>[] array1 = new Class[] {Object.class};
375 final Class<?>[] array1s = new Class[] {String.class};
376 final Class<?>[] array0 = new Class[] {};
377 final Class<?>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
378 final Class<?>[] arrayWrappers = { Integer.class, Boolean.class };
350379
351380 assertFalse(ClassUtils.isAssignable(array1, array2, true));
352381 assertFalse(ClassUtils.isAssignable(null, array2, true));
367396 assertTrue(ClassUtils.isAssignable(arrayWrappers, array2, true));
368397 }
369398
399 @Test
370400 public void test_isAssignable_ClassArray_ClassArray_NoAutoboxing() throws Exception {
371 Class<?>[] array2 = new Class[] {Object.class, Object.class};
372 Class<?>[] array1 = new Class[] {Object.class};
373 Class<?>[] array1s = new Class[] {String.class};
374 Class<?>[] array0 = new Class[] {};
375 Class<?>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
376 Class<?>[] arrayWrappers = { Integer.class, Boolean.class };
401 final Class<?>[] array2 = new Class[] {Object.class, Object.class};
402 final Class<?>[] array1 = new Class[] {Object.class};
403 final Class<?>[] array1s = new Class[] {String.class};
404 final Class<?>[] array0 = new Class[] {};
405 final Class<?>[] arrayPrimitives = { Integer.TYPE, Boolean.TYPE };
406 final Class<?>[] arrayWrappers = { Integer.class, Boolean.class };
377407
378408 assertFalse(ClassUtils.isAssignable(array1, array2, false));
379409 assertFalse(ClassUtils.isAssignable(null, array2, false));
394424 assertFalse(ClassUtils.isAssignable(arrayPrimitives, array2, false));
395425 }
396426
427 @Test
397428 public void test_isAssignable() throws Exception {
398429 assertFalse(ClassUtils.isAssignable((Class<?>) null, null));
399430 assertFalse(ClassUtils.isAssignable(String.class, null));
405436 assertTrue(ClassUtils.isAssignable(String.class, String.class));
406437 assertFalse(ClassUtils.isAssignable(Object.class, String.class));
407438
408 boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
439 final boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
409440
410441 assertEquals(autoboxing, ClassUtils.isAssignable(Integer.TYPE, Integer.class));
411442 assertEquals(autoboxing, ClassUtils.isAssignable(Integer.TYPE, Object.class));
421452 assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class));
422453 }
423454
455 @Test
424456 public void test_isAssignable_Autoboxing() throws Exception {
425457 assertFalse(ClassUtils.isAssignable((Class<?>) null, null, true));
426458 assertFalse(ClassUtils.isAssignable(String.class, null, true));
444476 assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class, true));
445477 }
446478
479 @Test
447480 public void test_isAssignable_NoAutoboxing() throws Exception {
448481 assertFalse(ClassUtils.isAssignable((Class<?>) null, null, false));
449482 assertFalse(ClassUtils.isAssignable(String.class, null, false));
467500 assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class, false));
468501 }
469502
503 @Test
470504 public void test_isAssignable_Widening() throws Exception {
471505 // test byte conversions
472506 assertFalse("byte -> char", ClassUtils.isAssignable(Byte.TYPE, Character.TYPE));
549583 assertTrue("boolean -> boolean", ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE));
550584 }
551585
586 @Test
552587 public void test_isAssignable_DefaultUnboxing_Widening() throws Exception {
553 boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
588 final boolean autoboxing = SystemUtils.isJavaVersionAtLeast(JAVA_1_5);
554589
555590 // test byte conversions
556591 assertFalse("byte -> char", ClassUtils.isAssignable(Byte.class, Character.TYPE));
633668 assertEquals("boolean -> boolean", autoboxing, ClassUtils.isAssignable(Boolean.class, Boolean.TYPE));
634669 }
635670
671 @Test
636672 public void test_isAssignable_Unboxing_Widening() throws Exception {
637673 // test byte conversions
638674 assertFalse("byte -> char", ClassUtils.isAssignable(Byte.class, Character.TYPE, true));
715751 assertTrue("boolean -> boolean", ClassUtils.isAssignable(Boolean.class, Boolean.TYPE, true));
716752 }
717753
754 @Test
718755 public void testIsPrimitiveOrWrapper() {
719756
720757 // test primitive wrapper classes
745782 assertFalse("this.getClass()", ClassUtils.isPrimitiveOrWrapper(this.getClass()));
746783 }
747784
785 @Test
748786 public void testIsPrimitiveWrapper() {
749787
750788 // test primitive wrapper classes
775813 assertFalse("this.getClass()", ClassUtils.isPrimitiveWrapper(this.getClass()));
776814 }
777815
816 @Test
778817 public void testPrimitiveToWrapper() {
779818
780819 // test primitive classes
809848 ClassUtils.primitiveToWrapper(null));
810849 }
811850
851 @Test
812852 public void testPrimitivesToWrappers() {
813853 // test null
814854 // assertNull("null -> null", ClassUtils.primitivesToWrappers(null)); // generates warning
815855 assertNull("null -> null", ClassUtils.primitivesToWrappers((Class<?>[]) null)); // equivalent cast to avoid warning
816856 // Other possible casts for null
817857 assertTrue("empty -> empty", Arrays.equals(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.primitivesToWrappers()));
818 Class<?>[] castNull = ClassUtils.primitivesToWrappers((Class<?>)null); // == new Class<?>[]{null}
858 final Class<?>[] castNull = ClassUtils.primitivesToWrappers((Class<?>)null); // == new Class<?>[]{null}
819859 assertTrue("(Class<?>)null -> [null]", Arrays.equals(new Class<?>[]{null}, castNull));
820860 // test empty array is returned unchanged
821861 // TODO this is not documented
822 assertEquals("empty -> empty",
862 assertArrayEquals("empty -> empty",
823863 ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.primitivesToWrappers(ArrayUtils.EMPTY_CLASS_ARRAY));
824864
825865 // test an array of various classes
828868 Integer.TYPE, Long.TYPE, Double.TYPE, Float.TYPE,
829869 String.class, ClassUtils.class
830870 };
831 Class<?>[] wrappers= ClassUtils.primitivesToWrappers(primitives);
871 final Class<?>[] wrappers= ClassUtils.primitivesToWrappers(primitives);
832872
833873 for (int i=0; i < primitives.length; i++) {
834874 // test each returned wrapper
835 Class<?> primitive = primitives[i];
836 Class<?> expectedWrapper = ClassUtils.primitiveToWrapper(primitive);
875 final Class<?> primitive = primitives[i];
876 final Class<?> expectedWrapper = ClassUtils.primitiveToWrapper(primitive);
837877
838878 assertEquals(primitive + " -> " + expectedWrapper, expectedWrapper, wrappers[i]);
839879 }
846886 assertNotSame("unmodified", noPrimitives, ClassUtils.primitivesToWrappers(noPrimitives));
847887 }
848888
889 @Test
849890 public void testWrapperToPrimitive() {
850891 // an array with classes to convert
851892 final Class<?>[] primitives = {
852893 Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE,
853894 Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE
854895 };
855 for (Class<?> primitive : primitives) {
856 Class<?> wrapperCls = ClassUtils.primitiveToWrapper(primitive);
896 for (final Class<?> primitive : primitives) {
897 final Class<?> wrapperCls = ClassUtils.primitiveToWrapper(primitive);
857898 assertFalse("Still primitive", wrapperCls.isPrimitive());
858899 assertEquals(wrapperCls + " -> " + primitive, primitive,
859900 ClassUtils.wrapperToPrimitive(wrapperCls));
860901 }
861902 }
862903
904 @Test
863905 public void testWrapperToPrimitiveNoWrapper() {
864906 assertNull("Wrong result for non wrapper class", ClassUtils.wrapperToPrimitive(String.class));
865907 }
866908
909 @Test
867910 public void testWrapperToPrimitiveNull() {
868911 assertNull("Wrong result for null class", ClassUtils.wrapperToPrimitive(null));
869912 }
870913
914 @Test
871915 public void testWrappersToPrimitives() {
872916 // an array with classes to test
873917 final Class<?>[] classes = {
876920 String.class, ClassUtils.class, null
877921 };
878922
879 Class<?>[] primitives = ClassUtils.wrappersToPrimitives(classes);
923 final Class<?>[] primitives = ClassUtils.wrappersToPrimitives(classes);
880924 // now test the result
881925 assertEquals("Wrong length of result array", classes.length, primitives.length);
882926 for (int i = 0; i < classes.length; i++) {
883 Class<?> expectedPrimitive = ClassUtils.wrapperToPrimitive(classes[i]);
927 final Class<?> expectedPrimitive = ClassUtils.wrapperToPrimitive(classes[i]);
884928 assertEquals(classes[i] + " -> " + expectedPrimitive, expectedPrimitive,
885929 primitives[i]);
886930 }
887931 }
888932
933 @Test
889934 public void testWrappersToPrimitivesNull() {
890935 // assertNull("Wrong result for null input", ClassUtils.wrappersToPrimitives(null)); // generates warning
891936 assertNull("Wrong result for null input", ClassUtils.wrappersToPrimitives((Class<?>[]) null)); // equivalent cast
892937 // Other possible casts for null
893938 assertTrue("empty -> empty", Arrays.equals(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.wrappersToPrimitives()));
894 Class<?>[] castNull = ClassUtils.wrappersToPrimitives((Class<?>)null); // == new Class<?>[]{null}
939 final Class<?>[] castNull = ClassUtils.wrappersToPrimitives((Class<?>)null); // == new Class<?>[]{null}
895940 assertTrue("(Class<?>)null -> [null]", Arrays.equals(new Class<?>[]{null}, castNull));
896941 }
897942
943 @Test
898944 public void testWrappersToPrimitivesEmpty() {
899 Class<?>[] empty = new Class[0];
900 assertEquals("Wrong result for empty input", empty, ClassUtils.wrappersToPrimitives(empty));
901 }
902
945 final Class<?>[] empty = new Class[0];
946 assertArrayEquals("Wrong result for empty input", empty, ClassUtils.wrappersToPrimitives(empty));
947 }
948
949 @Test
903950 public void testGetClassClassNotFound() throws Exception {
904951 assertGetClassThrowsClassNotFound( "bool" );
905952 assertGetClassThrowsClassNotFound( "bool[]" );
906953 assertGetClassThrowsClassNotFound( "integer[]" );
907954 }
908955
956 @Test
909957 public void testGetClassInvalidArguments() throws Exception {
910958 assertGetClassThrowsNullPointerException( null );
911959 assertGetClassThrowsClassNotFound( "[][][]" );
916964 assertGetClassThrowsClassNotFound( "hello..world" );
917965 }
918966
967 @Test
919968 public void testWithInterleavingWhitespace() throws ClassNotFoundException {
920969 assertEquals( int[].class, ClassUtils.getClass( " int [ ] " ) );
921970 assertEquals( long[].class, ClassUtils.getClass( "\rlong\t[\n]\r" ) );
923972 assertEquals( byte[].class, ClassUtils.getClass( "byte[\t\t\n\r] " ) );
924973 }
925974
975 @Test
926976 public void testGetInnerClass() throws ClassNotFoundException {
927977 assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest.Inner.DeeplyNested" ) );
928978 assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest.Inner$DeeplyNested" ) );
930980 assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest$Inner.DeeplyNested" ) );
931981 }
932982
983 @Test
933984 public void testGetClassByNormalNameArrays() throws ClassNotFoundException {
934985 assertEquals( int[].class, ClassUtils.getClass( "int[]" ) );
935986 assertEquals( long[].class, ClassUtils.getClass( "long[]" ) );
946997 assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "[Ljava.util.Map$Entry;" ) );
947998 }
948999
1000 @Test
9491001 public void testGetClassByNormalNameArrays2D() throws ClassNotFoundException {
9501002 assertEquals( int[][].class, ClassUtils.getClass( "int[][]" ) );
9511003 assertEquals( long[][].class, ClassUtils.getClass( "long[][]" ) );
9581010 assertEquals( String[][].class, ClassUtils.getClass( "java.lang.String[][]" ) );
9591011 }
9601012
1013 @Test
9611014 public void testGetClassWithArrayClasses2D() throws Exception {
9621015 assertGetClassReturnsClass( String[][].class );
9631016 assertGetClassReturnsClass( int[][].class );
9701023 assertGetClassReturnsClass( boolean[][].class );
9711024 }
9721025
1026 @Test
9731027 public void testGetClassWithArrayClasses() throws Exception {
9741028 assertGetClassReturnsClass( String[].class );
9751029 assertGetClassReturnsClass( int[].class );
9821036 assertGetClassReturnsClass( boolean[].class );
9831037 }
9841038
1039 @Test
9851040 public void testGetClassRawPrimitives() throws ClassNotFoundException {
9861041 assertEquals( int.class, ClassUtils.getClass( "int" ) );
9871042 assertEquals( long.class, ClassUtils.getClass( "long" ) );
9931048 assertEquals( boolean.class, ClassUtils.getClass( "boolean" ) );
9941049 }
9951050
996 private void assertGetClassReturnsClass( Class<?> c ) throws Exception {
1051 private void assertGetClassReturnsClass( final Class<?> c ) throws Exception {
9971052 assertEquals( c, ClassUtils.getClass( c.getName() ) );
9981053 }
9991054
1000 private void assertGetClassThrowsException( String className, Class<?> exceptionType ) throws Exception {
1055 private void assertGetClassThrowsException( final String className, final Class<?> exceptionType ) throws Exception {
10011056 try {
10021057 ClassUtils.getClass( className );
10031058 fail( "ClassUtils.getClass() should fail with an exception of type " + exceptionType.getName() + " when given class name \"" + className + "\"." );
10041059 }
1005 catch( Exception e ) {
1060 catch( final Exception e ) {
10061061 assertTrue( exceptionType.isAssignableFrom( e.getClass() ) );
10071062 }
10081063 }
10091064
1010 private void assertGetClassThrowsNullPointerException( String className ) throws Exception {
1065 private void assertGetClassThrowsNullPointerException( final String className ) throws Exception {
10111066 assertGetClassThrowsException( className, NullPointerException.class );
10121067 }
10131068
1014 private void assertGetClassThrowsClassNotFound( String className ) throws Exception {
1069 private void assertGetClassThrowsClassNotFound( final String className ) throws Exception {
10151070 assertGetClassThrowsException( className, ClassNotFoundException.class );
10161071 }
10171072
10181073 // Show the Java bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957
10191074 // We may have to delete this if a JDK fixes the bug.
1075 @Test
10201076 public void testShowJavaBug() throws Exception {
10211077 // Tests with Collections$UnmodifiableSet
1022 Set<?> set = Collections.unmodifiableSet(new HashSet<Object>());
1023 Method isEmptyMethod = set.getClass().getMethod("isEmpty", new Class[0]);
1078 final Set<?> set = Collections.unmodifiableSet(new HashSet<Object>());
1079 final Method isEmptyMethod = set.getClass().getMethod("isEmpty", new Class[0]);
10241080 try {
10251081 isEmptyMethod.invoke(set, new Object[0]);
10261082 fail("Failed to throw IllegalAccessException as expected");
1027 } catch(IllegalAccessException iae) {
1083 } catch(final IllegalAccessException iae) {
10281084 // expected
10291085 }
10301086 }
10311087
1088 @Test
10321089 public void testGetPublicMethod() throws Exception {
10331090 // Tests with Collections$UnmodifiableSet
1034 Set<?> set = Collections.unmodifiableSet(new HashSet<Object>());
1035 Method isEmptyMethod = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
1091 final Set<?> set = Collections.unmodifiableSet(new HashSet<Object>());
1092 final Method isEmptyMethod = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
10361093 assertTrue(Modifier.isPublic(isEmptyMethod.getDeclaringClass().getModifiers()));
10371094
10381095 try {
10391096 isEmptyMethod.invoke(set, new Object[0]);
1040 } catch(java.lang.IllegalAccessException iae) {
1097 } catch(final java.lang.IllegalAccessException iae) {
10411098 fail("Should not have thrown IllegalAccessException");
10421099 }
10431100
10441101 // Tests with a public Class
1045 Method toStringMethod = ClassUtils.getPublicMethod(Object.class, "toString", new Class[0]);
1102 final Method toStringMethod = ClassUtils.getPublicMethod(Object.class, "toString", new Class[0]);
10461103 assertEquals(Object.class.getMethod("toString", new Class[0]), toStringMethod);
10471104 }
10481105
1106 @Test
10491107 public void testToClass_object() {
10501108 // assertNull(ClassUtils.toClass(null)); // generates warning
10511109 assertNull(ClassUtils.toClass((Object[]) null)); // equivalent explicit cast
10521110
10531111 // Additional varargs tests
10541112 assertTrue("empty -> empty", Arrays.equals(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.toClass()));
1055 Class<?>[] castNull = ClassUtils.toClass((Object) null); // == new Object[]{null}
1113 final Class<?>[] castNull = ClassUtils.toClass((Object) null); // == new Object[]{null}
10561114 assertTrue("(Object)null -> [null]", Arrays.equals(new Object[]{null}, castNull));
10571115
10581116 assertSame(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.toClass(ArrayUtils.EMPTY_OBJECT_ARRAY));
10641122 ClassUtils.toClass(new Object[] { "Test", null, Double.valueOf(99d) })));
10651123 }
10661124
1125 @Test
10671126 public void test_getShortCanonicalName_Object() {
10681127 assertEquals("<null>", ClassUtils.getShortCanonicalName(null, "<null>"));
10691128 assertEquals("ClassUtils", ClassUtils.getShortCanonicalName(new ClassUtils(), "<null>"));
10791138 assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortCanonicalName(new Inner(), "<null>"));
10801139 }
10811140
1141 @Test
10821142 public void test_getShortCanonicalName_Class() {
10831143 assertEquals("ClassUtils", ClassUtils.getShortCanonicalName(ClassUtils.class));
10841144 assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName(ClassUtils[].class));
10931153 assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortCanonicalName(Inner.class));
10941154 }
10951155
1156 @Test
10961157 public void test_getShortCanonicalName_String() {
10971158 assertEquals("ClassUtils", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtils"));
10981159 assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName("[Lorg.apache.commons.lang3.ClassUtils;"));
11101171 assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortCanonicalName("org.apache.commons.lang3.ClassUtilsTest$Inner"));
11111172 }
11121173
1174 @Test
11131175 public void test_getPackageCanonicalName_Object() {
11141176 assertEquals("<null>", ClassUtils.getPackageCanonicalName(null, "<null>"));
11151177 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new ClassUtils(), "<null>"));
11251187 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(new Inner(), "<null>"));
11261188 }
11271189
1190 @Test
11281191 public void test_getPackageCanonicalName_Class() {
11291192 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(ClassUtils.class));
11301193 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(ClassUtils[].class));
11391202 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName(Inner.class));
11401203 }
11411204
1205 @Test
11421206 public void test_getPackageCanonicalName_String() {
11431207 assertEquals("org.apache.commons.lang3",
11441208 ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtils"));
11611225 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageCanonicalName("org.apache.commons.lang3.ClassUtilsTest$Inner"));
11621226 }
11631227
1228 @Test
1229 public void testHierarchyIncludingInterfaces() {
1230 final Iterator<Class<?>> iter =
1231 ClassUtils.hierarchy(StringParameterizedChild.class, Interfaces.INCLUDE).iterator();
1232 assertEquals(StringParameterizedChild.class, iter.next());
1233 assertEquals(GenericParent.class, iter.next());
1234 assertEquals(GenericConsumer.class, iter.next());
1235 assertEquals(Object.class, iter.next());
1236 assertFalse(iter.hasNext());
1237 }
1238
1239 @Test
1240 public void testHierarchyExcludingInterfaces() {
1241 final Iterator<Class<?>> iter = ClassUtils.hierarchy(StringParameterizedChild.class).iterator();
1242 assertEquals(StringParameterizedChild.class, iter.next());
1243 assertEquals(GenericParent.class, iter.next());
1244 assertEquals(Object.class, iter.next());
1245 assertFalse(iter.hasNext());
1246 }
11641247 }
0 /*******************************************************************************
1 * Licensed to the Apache Software Foundation (ASF) under one
2 * or more contributor license agreements. See the NOTICE file
3 * distributed with this work for additional information
4 * regarding copyright ownership. The ASF licenses this file
5 * to you under the Apache License, Version 2.0 (the
6 * "License"); you may not use this file except in compliance
7 * with the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing,
12 * software distributed under the License is distributed on an
13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 * KIND, either express or implied. See the License for the
15 * specific language governing permissions and limitations
16 * under the License.
17 *******************************************************************************/
18 package org.apache.commons.lang3;
19
20 import static org.junit.Assert.assertArrayEquals;
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.fail;
23
24 import java.util.UUID;
25
26 import org.junit.Test;
27
28
29 /**
30 * Unit tests {@link Conversion}.
31 *
32 * @version $Id: ConversionTest.java 1436770 2013-01-22 07:09:45Z ggregory $
33 */
34 public class ConversionTest {
35
36 /**
37 * Tests {@link Conversion#hexDigitToInt(char)}.
38 */
39 @Test
40 public void testHexDigitToInt() {
41 assertEquals(0, Conversion.hexDigitToInt('0'));
42 assertEquals(1, Conversion.hexDigitToInt('1'));
43 assertEquals(2, Conversion.hexDigitToInt('2'));
44 assertEquals(3, Conversion.hexDigitToInt('3'));
45 assertEquals(4, Conversion.hexDigitToInt('4'));
46 assertEquals(5, Conversion.hexDigitToInt('5'));
47 assertEquals(6, Conversion.hexDigitToInt('6'));
48 assertEquals(7, Conversion.hexDigitToInt('7'));
49 assertEquals(8, Conversion.hexDigitToInt('8'));
50 assertEquals(9, Conversion.hexDigitToInt('9'));
51 assertEquals(10, Conversion.hexDigitToInt('A'));
52 assertEquals(10, Conversion.hexDigitToInt('a'));
53 assertEquals(11, Conversion.hexDigitToInt('B'));
54 assertEquals(11, Conversion.hexDigitToInt('b'));
55 assertEquals(12, Conversion.hexDigitToInt('C'));
56 assertEquals(12, Conversion.hexDigitToInt('c'));
57 assertEquals(13, Conversion.hexDigitToInt('D'));
58 assertEquals(13, Conversion.hexDigitToInt('d'));
59 assertEquals(14, Conversion.hexDigitToInt('E'));
60 assertEquals(14, Conversion.hexDigitToInt('e'));
61 assertEquals(15, Conversion.hexDigitToInt('F'));
62 assertEquals(15, Conversion.hexDigitToInt('f'));
63 try {
64 Conversion.hexDigitToInt('G');
65 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
66 } catch (final IllegalArgumentException e) {
67 // OK
68 }
69 }
70
71 /**
72 * Tests {@link Conversion#hexDigitMsb0ToInt(char)}.
73 */
74 @Test
75 public void testHexDigitMsb0ToInt() {
76 assertEquals(0x0, Conversion.hexDigitMsb0ToInt('0'));
77 assertEquals(0x8, Conversion.hexDigitMsb0ToInt('1'));
78 assertEquals(0x4, Conversion.hexDigitMsb0ToInt('2'));
79 assertEquals(0xC, Conversion.hexDigitMsb0ToInt('3'));
80 assertEquals(0x2, Conversion.hexDigitMsb0ToInt('4'));
81 assertEquals(0xA, Conversion.hexDigitMsb0ToInt('5'));
82 assertEquals(0x6, Conversion.hexDigitMsb0ToInt('6'));
83 assertEquals(0xE, Conversion.hexDigitMsb0ToInt('7'));
84 assertEquals(0x1, Conversion.hexDigitMsb0ToInt('8'));
85 assertEquals(0x9, Conversion.hexDigitMsb0ToInt('9'));
86 assertEquals(0x5, Conversion.hexDigitMsb0ToInt('A'));
87 assertEquals(0x5, Conversion.hexDigitMsb0ToInt('a'));
88 assertEquals(0xD, Conversion.hexDigitMsb0ToInt('B'));
89 assertEquals(0xD, Conversion.hexDigitMsb0ToInt('b'));
90 assertEquals(0x3, Conversion.hexDigitMsb0ToInt('C'));
91 assertEquals(0x3, Conversion.hexDigitMsb0ToInt('c'));
92 assertEquals(0xB, Conversion.hexDigitMsb0ToInt('D'));
93 assertEquals(0xB, Conversion.hexDigitMsb0ToInt('d'));
94 assertEquals(0x7, Conversion.hexDigitMsb0ToInt('E'));
95 assertEquals(0x7, Conversion.hexDigitMsb0ToInt('e'));
96 assertEquals(0xF, Conversion.hexDigitMsb0ToInt('F'));
97 assertEquals(0xF, Conversion.hexDigitMsb0ToInt('f'));
98 try {
99 Conversion.hexDigitMsb0ToInt('G');
100 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
101 } catch (final IllegalArgumentException e) {
102 // OK
103 }
104 }
105
106 /**
107 * Tests {@link Conversion#hexDigitToBinary(char)}.
108 */
109 @Test
110 public void testHexDigitToBinary() {
111 assertBinaryEquals(
112 new boolean[]{false, false, false, false}, Conversion.hexDigitToBinary('0'));
113 assertBinaryEquals(
114 new boolean[]{true, false, false, false}, Conversion.hexDigitToBinary('1'));
115 assertBinaryEquals(
116 new boolean[]{false, true, false, false}, Conversion.hexDigitToBinary('2'));
117 assertBinaryEquals(
118 new boolean[]{true, true, false, false}, Conversion.hexDigitToBinary('3'));
119 assertBinaryEquals(
120 new boolean[]{false, false, true, false}, Conversion.hexDigitToBinary('4'));
121 assertBinaryEquals(
122 new boolean[]{true, false, true, false}, Conversion.hexDigitToBinary('5'));
123 assertBinaryEquals(
124 new boolean[]{false, true, true, false}, Conversion.hexDigitToBinary('6'));
125 assertBinaryEquals(
126 new boolean[]{true, true, true, false}, Conversion.hexDigitToBinary('7'));
127 assertBinaryEquals(
128 new boolean[]{false, false, false, true}, Conversion.hexDigitToBinary('8'));
129 assertBinaryEquals(
130 new boolean[]{true, false, false, true}, Conversion.hexDigitToBinary('9'));
131 assertBinaryEquals(
132 new boolean[]{false, true, false, true}, Conversion.hexDigitToBinary('A'));
133 assertBinaryEquals(
134 new boolean[]{false, true, false, true}, Conversion.hexDigitToBinary('a'));
135 assertBinaryEquals(
136 new boolean[]{true, true, false, true}, Conversion.hexDigitToBinary('B'));
137 assertBinaryEquals(
138 new boolean[]{true, true, false, true}, Conversion.hexDigitToBinary('b'));
139 assertBinaryEquals(
140 new boolean[]{false, false, true, true}, Conversion.hexDigitToBinary('C'));
141 assertBinaryEquals(
142 new boolean[]{false, false, true, true}, Conversion.hexDigitToBinary('c'));
143 assertBinaryEquals(
144 new boolean[]{true, false, true, true}, Conversion.hexDigitToBinary('D'));
145 assertBinaryEquals(
146 new boolean[]{true, false, true, true}, Conversion.hexDigitToBinary('d'));
147 assertBinaryEquals(
148 new boolean[]{false, true, true, true}, Conversion.hexDigitToBinary('E'));
149 assertBinaryEquals(
150 new boolean[]{false, true, true, true}, Conversion.hexDigitToBinary('e'));
151 assertBinaryEquals(
152 new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('F'));
153 assertBinaryEquals(
154 new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('f'));
155 try {
156 Conversion.hexDigitToBinary('G');
157 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
158 } catch (final IllegalArgumentException e) {
159 // OK
160 }
161 }
162
163 /**
164 * Tests {@link Conversion#hexDigitMsb0ToBinary(char)}.
165 */
166 @Test
167 public void testHexDigitMsb0ToBinary() {
168 assertBinaryEquals(
169 new boolean[]{false, false, false, false}, Conversion.hexDigitMsb0ToBinary('0'));
170 assertBinaryEquals(
171 new boolean[]{false, false, false, true}, Conversion.hexDigitMsb0ToBinary('1'));
172 assertBinaryEquals(
173 new boolean[]{false, false, true, false}, Conversion.hexDigitMsb0ToBinary('2'));
174 assertBinaryEquals(
175 new boolean[]{false, false, true, true}, Conversion.hexDigitMsb0ToBinary('3'));
176 assertBinaryEquals(
177 new boolean[]{false, true, false, false}, Conversion.hexDigitMsb0ToBinary('4'));
178 assertBinaryEquals(
179 new boolean[]{false, true, false, true}, Conversion.hexDigitMsb0ToBinary('5'));
180 assertBinaryEquals(
181 new boolean[]{false, true, true, false}, Conversion.hexDigitMsb0ToBinary('6'));
182 assertBinaryEquals(
183 new boolean[]{false, true, true, true}, Conversion.hexDigitMsb0ToBinary('7'));
184 assertBinaryEquals(
185 new boolean[]{true, false, false, false}, Conversion.hexDigitMsb0ToBinary('8'));
186 assertBinaryEquals(
187 new boolean[]{true, false, false, true}, Conversion.hexDigitMsb0ToBinary('9'));
188 assertBinaryEquals(
189 new boolean[]{true, false, true, false}, Conversion.hexDigitMsb0ToBinary('A'));
190 assertBinaryEquals(
191 new boolean[]{true, false, true, false}, Conversion.hexDigitMsb0ToBinary('a'));
192 assertBinaryEquals(
193 new boolean[]{true, false, true, true}, Conversion.hexDigitMsb0ToBinary('B'));
194 assertBinaryEquals(
195 new boolean[]{true, false, true, true}, Conversion.hexDigitMsb0ToBinary('b'));
196 assertBinaryEquals(
197 new boolean[]{true, true, false, false}, Conversion.hexDigitMsb0ToBinary('C'));
198 assertBinaryEquals(
199 new boolean[]{true, true, false, false}, Conversion.hexDigitMsb0ToBinary('c'));
200 assertBinaryEquals(
201 new boolean[]{true, true, false, true}, Conversion.hexDigitMsb0ToBinary('D'));
202 assertBinaryEquals(
203 new boolean[]{true, true, false, true}, Conversion.hexDigitMsb0ToBinary('d'));
204 assertBinaryEquals(
205 new boolean[]{true, true, true, false}, Conversion.hexDigitMsb0ToBinary('E'));
206 assertBinaryEquals(
207 new boolean[]{true, true, true, false}, Conversion.hexDigitMsb0ToBinary('e'));
208 assertBinaryEquals(
209 new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('F'));
210 assertBinaryEquals(
211 new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('f'));
212 try {
213 Conversion.hexDigitMsb0ToBinary('G');
214 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
215 } catch (final IllegalArgumentException e) {
216 // OK
217 }
218 }
219
220 /**
221 * Tests {@link Conversion#binaryToHexDigit(boolean[])}.
222 */
223 @Test
224 public void testBinaryToHexDigit() {
225 assertEquals(
226 '0', Conversion.binaryToHexDigit(new boolean[]{false, false, false, false}));
227 assertEquals('1', Conversion.binaryToHexDigit(new boolean[]{true, false, false, false}));
228 assertEquals('2', Conversion.binaryToHexDigit(new boolean[]{false, true, false, false}));
229 assertEquals('3', Conversion.binaryToHexDigit(new boolean[]{true, true, false, false}));
230 assertEquals('4', Conversion.binaryToHexDigit(new boolean[]{false, false, true, false}));
231 assertEquals('5', Conversion.binaryToHexDigit(new boolean[]{true, false, true, false}));
232 assertEquals('6', Conversion.binaryToHexDigit(new boolean[]{false, true, true, false}));
233 assertEquals('7', Conversion.binaryToHexDigit(new boolean[]{true, true, true, false}));
234 assertEquals('8', Conversion.binaryToHexDigit(new boolean[]{false, false, false, true}));
235 assertEquals('9', Conversion.binaryToHexDigit(new boolean[]{true, false, false, true}));
236 assertEquals('a', Conversion.binaryToHexDigit(new boolean[]{false, true, false, true}));
237 assertEquals('b', Conversion.binaryToHexDigit(new boolean[]{true, true, false, true}));
238 assertEquals('c', Conversion.binaryToHexDigit(new boolean[]{false, false, true, true}));
239 assertEquals('d', Conversion.binaryToHexDigit(new boolean[]{true, false, true, true}));
240 assertEquals('e', Conversion.binaryToHexDigit(new boolean[]{false, true, true, true}));
241 assertEquals('f', Conversion.binaryToHexDigit(new boolean[]{true, true, true, true}));
242 assertEquals('1', Conversion.binaryToHexDigit(new boolean[]{true}));
243 assertEquals(
244 'f', Conversion.binaryToHexDigit(new boolean[]{true, true, true, true, true}));
245 try {
246 Conversion.binaryToHexDigit(new boolean[]{});
247 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
248 } catch (final IllegalArgumentException e) {
249 // OK
250 }
251 }
252
253 /**
254 * Tests {@link Conversion#binaryBeMsb0ToHexDigit(boolean[], int)}.
255 */
256 @Test
257 public void testBinaryToHexDigit_2args() {
258 final boolean[] shortArray = new boolean[]{false, true, true};
259 assertEquals('6', Conversion.binaryToHexDigit(shortArray, 0));
260 assertEquals('3', Conversion.binaryToHexDigit(shortArray, 1));
261 assertEquals('1', Conversion.binaryToHexDigit(shortArray, 2));
262 final boolean[] longArray = new boolean[]{true, false, true, false, false, true, true};
263 assertEquals('5', Conversion.binaryToHexDigit(longArray, 0));
264 assertEquals('2', Conversion.binaryToHexDigit(longArray, 1));
265 assertEquals('9', Conversion.binaryToHexDigit(longArray, 2));
266 assertEquals('c', Conversion.binaryToHexDigit(longArray, 3));
267 assertEquals('6', Conversion.binaryToHexDigit(longArray, 4));
268 assertEquals('3', Conversion.binaryToHexDigit(longArray, 5));
269 assertEquals('1', Conversion.binaryToHexDigit(longArray, 6));
270 }
271
272 /**
273 * Tests {@link Conversion#binaryToHexDigitMsb0_4bits(boolean[])}.
274 */
275 @Test
276 public void testBinaryToHexDigitMsb0_bits() {
277 assertEquals(
278 '0',
279 Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, false, false}));
280 assertEquals(
281 '1',
282 Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, false, true}));
283 assertEquals(
284 '2',
285 Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, true, false}));
286 assertEquals(
287 '3', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, true, true}));
288 assertEquals(
289 '4',
290 Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, false, false}));
291 assertEquals(
292 '5', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, false, true}));
293 assertEquals(
294 '6', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, true, false}));
295 assertEquals(
296 '7', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, true, true}));
297 assertEquals(
298 '8',
299 Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, false, false}));
300 assertEquals(
301 '9', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, false, true}));
302 assertEquals(
303 'a', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, true, false}));
304 assertEquals(
305 'b', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, true, true}));
306 assertEquals(
307 'c', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, false, false}));
308 assertEquals(
309 'd', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, false, true}));
310 assertEquals(
311 'e', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, false}));
312 assertEquals(
313 'f', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, true}));
314 try {
315 Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{});
316 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
317 } catch (final IllegalArgumentException e) {
318 // OK
319 }
320 }
321
322 /**
323 * Tests {@link Conversion#binaryToHexDigitMsb0_4bits(boolean[], int)}.
324 */
325 @Test
326 public void testBinaryToHexDigitMsb0_4bits_2args() {
327 // boolean[] shortArray = new boolean[]{true,true,false};
328 // assertEquals('6', Conversion.BinaryToHexDigitMsb0(shortArray,0));
329 // assertEquals('3', Conversion.BinaryToHexDigitMsb0(shortArray,1));
330 // assertEquals('1', Conversion.BinaryToHexDigitMsb0(shortArray,2));
331 final boolean[] shortArray = new boolean[]{true, true, false, true};
332 assertEquals('d', Conversion.binaryToHexDigitMsb0_4bits(shortArray, 0));
333 final boolean[] longArray = new boolean[]{true, false, true, false, false, true, true};
334 assertEquals('a', Conversion.binaryToHexDigitMsb0_4bits(longArray, 0));
335 assertEquals('4', Conversion.binaryToHexDigitMsb0_4bits(longArray, 1));
336 assertEquals('9', Conversion.binaryToHexDigitMsb0_4bits(longArray, 2));
337 assertEquals('3', Conversion.binaryToHexDigitMsb0_4bits(longArray, 3));
338 // assertEquals('6', Conversion.BinaryToHexDigitMsb0(longArray,4));
339 // assertEquals('3', Conversion.BinaryToHexDigitMsb0(longArray,5));
340 // assertEquals('1', Conversion.BinaryToHexDigitMsb0(longArray,6));
341 final boolean[] maxLengthArray = new boolean[]{
342 true, false, true, false, false, true, true, true};
343 assertEquals('a', Conversion.binaryToHexDigitMsb0_4bits(maxLengthArray, 0));
344 assertEquals('4', Conversion.binaryToHexDigitMsb0_4bits(maxLengthArray, 1));
345 assertEquals('9', Conversion.binaryToHexDigitMsb0_4bits(maxLengthArray, 2));
346 assertEquals('3', Conversion.binaryToHexDigitMsb0_4bits(maxLengthArray, 3));
347 assertEquals('7', Conversion.binaryToHexDigitMsb0_4bits(maxLengthArray, 4));
348 // assertEquals('7', Conversion.BinaryToHexDigitMsb0(longArray,5));
349 // assertEquals('3', Conversion.BinaryToHexDigitMsb0(longArray,6));
350 // assertEquals('1', Conversion.BinaryToHexDigitMsb0(longArray,7));
351 final boolean[] javaDocCheck = new boolean[]{
352 true, false, false, true, true, false, true, false};
353 assertEquals('d', Conversion.binaryToHexDigitMsb0_4bits(javaDocCheck, 3));
354
355 }
356
357 /**
358 * Tests {@link Conversion#binaryToHexDigit(boolean[])}.
359 */
360 @Test
361 public void testBinaryBeMsb0ToHexDigit() {
362 assertEquals(
363 '0', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, false, false}));
364 assertEquals(
365 '1', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, false, true}));
366 assertEquals(
367 '2', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, true, false}));
368 assertEquals(
369 '3', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, true, true}));
370 assertEquals(
371 '4', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, false, false}));
372 assertEquals(
373 '5', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, false, true}));
374 assertEquals(
375 '6', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, true, false}));
376 assertEquals(
377 '7', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, true, true}));
378 assertEquals(
379 '8', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, false, false}));
380 assertEquals(
381 '9', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, false, true}));
382 assertEquals(
383 'a', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, true, false}));
384 assertEquals(
385 'b', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, true, true}));
386 assertEquals(
387 'c', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, false, false}));
388 assertEquals(
389 'd', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, false, true}));
390 assertEquals(
391 'e', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, true, false}));
392 assertEquals(
393 'f', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, true, true}));
394 assertEquals(
395 '4',
396 Conversion.binaryBeMsb0ToHexDigit(new boolean[]{
397 true, false, false, false, false, false, false, false, false, false, false,
398 false, false, true, false, false}));
399 try {
400 Conversion.binaryBeMsb0ToHexDigit(new boolean[]{});
401 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
402 } catch (final IllegalArgumentException e) {
403 // OK
404 }
405 }
406
407 /**
408 * Tests {@link Conversion#binaryToHexDigit(boolean[], int)}.
409 */
410 @Test
411 public void testBinaryBeMsb0ToHexDigit_2args() {
412 assertEquals(
413 '5',
414 Conversion.binaryBeMsb0ToHexDigit(new boolean[]{
415 true, false, false, false, false, false, false, false, false, false, false,
416 true, false, true, false, false}, 2));
417
418 final boolean[] shortArray = new boolean[]{true, true, false};
419 assertEquals('6', Conversion.binaryBeMsb0ToHexDigit(shortArray, 0));
420 assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray, 1));
421 assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray, 2));
422 final boolean[] shortArray2 = new boolean[]{true, true, true, false, false, true, false, true};
423 assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 0));
424 assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 1));
425 assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 2));
426 assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 3));
427 assertEquals('e', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 4));
428 assertEquals('7', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 5));
429 assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 6));
430 assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 7));
431 final boolean[] multiBytesArray = new boolean[]{
432 true, true, false, false, true, false, true, false, true, true, true, false, false,
433 true, false, true};
434 assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 0));
435 assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 1));
436 assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 2));
437 assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 3));
438 assertEquals('e', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 4));
439 assertEquals('7', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 5));
440 assertEquals('b', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 6));
441 assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 7));
442
443 assertEquals('a', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 8));
444 assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 9));
445 assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 10));
446 assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 11));
447 assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 12));
448 assertEquals('6', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 13));
449 assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 14));
450 assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 15));
451
452 }
453
454 /**
455 * Tests {@link Conversion#intToHexDigit(int)}.
456 */
457 @Test
458 public void testIntToHexDigit() {
459 assertEquals('0', Conversion.intToHexDigit(0));
460 assertEquals('1', Conversion.intToHexDigit(1));
461 assertEquals('2', Conversion.intToHexDigit(2));
462 assertEquals('3', Conversion.intToHexDigit(3));
463 assertEquals('4', Conversion.intToHexDigit(4));
464 assertEquals('5', Conversion.intToHexDigit(5));
465 assertEquals('6', Conversion.intToHexDigit(6));
466 assertEquals('7', Conversion.intToHexDigit(7));
467 assertEquals('8', Conversion.intToHexDigit(8));
468 assertEquals('9', Conversion.intToHexDigit(9));
469 assertEquals('a', Conversion.intToHexDigit(10));
470 assertEquals('b', Conversion.intToHexDigit(11));
471 assertEquals('c', Conversion.intToHexDigit(12));
472 assertEquals('d', Conversion.intToHexDigit(13));
473 assertEquals('e', Conversion.intToHexDigit(14));
474 assertEquals('f', Conversion.intToHexDigit(15));
475 try {
476 Conversion.intToHexDigit(16);
477 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
478 } catch (final IllegalArgumentException e) {
479 // OK
480 }
481 }
482
483 /**
484 * Tests {@link Conversion#intToHexDigitMsb0(int)}.
485 */
486 @Test
487 public void testIntToHexDigitMsb0() {
488 assertEquals('0', Conversion.intToHexDigitMsb0(0));
489 assertEquals('8', Conversion.intToHexDigitMsb0(1));
490 assertEquals('4', Conversion.intToHexDigitMsb0(2));
491 assertEquals('c', Conversion.intToHexDigitMsb0(3));
492 assertEquals('2', Conversion.intToHexDigitMsb0(4));
493 assertEquals('a', Conversion.intToHexDigitMsb0(5));
494 assertEquals('6', Conversion.intToHexDigitMsb0(6));
495 assertEquals('e', Conversion.intToHexDigitMsb0(7));
496 assertEquals('1', Conversion.intToHexDigitMsb0(8));
497 assertEquals('9', Conversion.intToHexDigitMsb0(9));
498 assertEquals('5', Conversion.intToHexDigitMsb0(10));
499 assertEquals('d', Conversion.intToHexDigitMsb0(11));
500 assertEquals('3', Conversion.intToHexDigitMsb0(12));
501 assertEquals('b', Conversion.intToHexDigitMsb0(13));
502 assertEquals('7', Conversion.intToHexDigitMsb0(14));
503 assertEquals('f', Conversion.intToHexDigitMsb0(15));
504 try {
505 Conversion.intToHexDigitMsb0(16);
506 fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
507 } catch (final IllegalArgumentException e) {
508 // OK
509 }
510 }
511
512 static String dbgPrint(final boolean[] src) {
513 final StringBuilder sb = new StringBuilder();
514 for (final boolean e : src) {
515 if (e) {
516 sb.append("1,");
517 } else {
518 sb.append("0,");
519 }
520 }
521 final String out = sb.toString();
522 return out.substring(0, out.length() - 1);
523 }
524
525 // org.junit.Assert(boolean[], boolean[]) does not exist in JUnit 4.2
526 static void assertBinaryEquals(final boolean[] expected, final boolean[] actual) {
527 assertEquals(expected.length, actual.length);
528 for (int i = 0; i < expected.length; i++ ) {
529 try {
530 assertEquals(expected[i], actual[i]);
531 } catch (final Throwable e) {
532 final String msg = "Mismatch at index "
533 + i
534 + " between:\n"
535 + dbgPrint(expected)
536 + " and\n"
537 + dbgPrint(actual);
538 fail(msg + "\n" + e.getMessage());
539 }
540 }
541 }
542
543 /**
544 * Tests {@link Conversion#intArrayToLong(int[], int, long, int, int)}.
545 */
546 @Test
547 public void testIntArrayToLong() {
548 final int[] src = new int[]{0xCDF1F0C1, 0x0F123456, 0x78000000};
549 assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 0, 0L, 0, 0));
550 assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 1, 0L, 0, 0));
551 assertEquals(0x00000000CDF1F0C1L, Conversion.intArrayToLong(src, 0, 0L, 0, 1));
552 assertEquals(0x0F123456CDF1F0C1L, Conversion.intArrayToLong(src, 0, 0L, 0, 2));
553 assertEquals(0x000000000F123456L, Conversion.intArrayToLong(src, 1, 0L, 0, 1));
554 assertEquals(
555 0x123456789ABCDEF0L, Conversion.intArrayToLong(src, 0, 0x123456789ABCDEF0L, 0, 0));
556 assertEquals(
557 0x1234567878000000L, Conversion.intArrayToLong(src, 2, 0x123456789ABCDEF0L, 0, 1));
558 // assertEquals(0x0F12345678000000L,Conversion.intsToLong(src,1,0x123456789ABCDEF0L,32,2));
559 }
560
561 /**
562 * Tests {@link Conversion#shortArrayToLong(short[], int, long, int, int)}.
563 */
564 @Test
565 public void testShortArrayToLong() {
566 final short[] src = new short[]{
567 (short)0xCDF1, (short)0xF0C1, (short)0x0F12, (short)0x3456, (short)0x7800};
568 assertEquals(0x0000000000000000L, Conversion.shortArrayToLong(src, 0, 0L, 0, 0));
569 assertEquals(0x000000000000CDF1L, Conversion.shortArrayToLong(src, 0, 0L, 0, 1));
570 assertEquals(0x00000000F0C1CDF1L, Conversion.shortArrayToLong(src, 0, 0L, 0, 2));
571 assertEquals(0x780034560F12F0C1L, Conversion.shortArrayToLong(src, 1, 0L, 0, 4));
572 assertEquals(
573 0x123456789ABCDEF0L, Conversion.shortArrayToLong(src, 0, 0x123456789ABCDEF0L, 0, 0));
574 assertEquals(
575 0x123456CDF1BCDEF0L,
576 Conversion.shortArrayToLong(src, 0, 0x123456789ABCDEF0L, 24, 1));
577 assertEquals(
578 0x123478003456DEF0L,
579 Conversion.shortArrayToLong(src, 3, 0x123456789ABCDEF0L, 16, 2));
580 }
581
582 /**
583 * Tests {@link Conversion#byteArrayToLong(byte[], int, long, int, int)}.
584 */
585 @Test
586 public void testByteArrayToLong() {
587 final byte[] src = new byte[]{
588 (byte)0xCD, (byte)0xF1, (byte)0xF0, (byte)0xC1, (byte)0x0F, (byte)0x12, (byte)0x34,
589 (byte)0x56, (byte)0x78};
590 assertEquals(0x0000000000000000L, Conversion.byteArrayToLong(src, 0, 0L, 0, 0));
591 assertEquals(0x00000000000000CDL, Conversion.byteArrayToLong(src, 0, 0L, 0, 1));
592 assertEquals(0x00000000C1F0F1CDL, Conversion.byteArrayToLong(src, 0, 0L, 0, 4));
593 assertEquals(0x000000000FC1F0F1L, Conversion.byteArrayToLong(src, 1, 0L, 0, 4));
594 assertEquals(
595 0x123456789ABCDEF0L, Conversion.byteArrayToLong(src, 0, 0x123456789ABCDEF0L, 0, 0));
596 assertEquals(
597 0x12345678CDBCDEF0L, Conversion.byteArrayToLong(src, 0, 0x123456789ABCDEF0L, 24, 1));
598 assertEquals(
599 0x123456789A7856F0L, Conversion.byteArrayToLong(src, 7, 0x123456789ABCDEF0L, 8, 2));
600 }
601
602 /**
603 * Tests {@link Conversion#shortArrayToInt(short[], int, int, int, int)}.
604 */
605 @Test
606 public void testShortArrayToInt() {
607 final short[] src = new short[]{
608 (short)0xCDF1, (short)0xF0C1, (short)0x0F12, (short)0x3456, (short)0x7800};
609 assertEquals(0x00000000, Conversion.shortArrayToInt(src, 0, 0, 0, 0));
610 assertEquals(0x0000CDF1, Conversion.shortArrayToInt(src, 0, 0, 0, 1));
611 assertEquals(0xF0C1CDF1, Conversion.shortArrayToInt(src, 0, 0, 0, 2));
612 assertEquals(0x0F12F0C1, Conversion.shortArrayToInt(src, 1, 0, 0, 2));
613 assertEquals(0x12345678, Conversion.shortArrayToInt(src, 0, 0x12345678, 0, 0));
614 assertEquals(0xCDF15678, Conversion.shortArrayToInt(src, 0, 0x12345678, 16, 1));
615 // assertEquals(0x34567800,Conversion.ShortArrayToInt(src, 3, 0x12345678, 16, 2));
616 }
617
618 /**
619 * Tests {@link Conversion#byteArrayToInt(byte[], int, int, int, int)}.
620 */
621 @Test
622 public void testByteArrayToInt() {
623 final byte[] src = new byte[]{
624 (byte)0xCD, (byte)0xF1, (byte)0xF0, (byte)0xC1, (byte)0x0F, (byte)0x12, (byte)0x34,
625 (byte)0x56, (byte)0x78};
626 assertEquals(0x00000000, Conversion.byteArrayToInt(src, 0, 0, 0, 0));
627 assertEquals(0x000000CD, Conversion.byteArrayToInt(src, 0, 0, 0, 1));
628 assertEquals(0xC1F0F1CD, Conversion.byteArrayToInt(src, 0, 0, 0, 4));
629 assertEquals(0x0FC1F0F1, Conversion.byteArrayToInt(src, 1, 0, 0, 4));
630 assertEquals(0x12345678, Conversion.byteArrayToInt(src, 0, 0x12345678, 0, 0));
631 assertEquals(0xCD345678, Conversion.byteArrayToInt(src, 0, 0x12345678, 24, 1));
632 // assertEquals(0x56341278,Conversion.ByteArrayToInt(src, 5, 0x01234567, 8, 4));
633 }
634
635 /**
636 * Tests {@link Conversion#byteArrayToShort(byte[], int, short, int, int)}.
637 */
638 @Test
639 public void testByteArrayToShort() {
640 final byte[] src = new byte[]{
641 (byte)0xCD, (byte)0xF1, (byte)0xF0, (byte)0xC1, (byte)0x0F, (byte)0x12, (byte)0x34,
642 (byte)0x56, (byte)0x78};
643 assertEquals((short)0x0000, Conversion.byteArrayToShort(src, 0, (short)0, 0, 0));
644 assertEquals((short)0x00CD, Conversion.byteArrayToShort(src, 0, (short)0, 0, 1));
645 assertEquals((short)0xF1CD, Conversion.byteArrayToShort(src, 0, (short)0, 0, 2));
646 assertEquals((short)0xF0F1, Conversion.byteArrayToShort(src, 1, (short)0, 0, 2));
647 assertEquals((short)0x1234, Conversion.byteArrayToShort(src, 0, (short)0x1234, 0, 0));
648 assertEquals((short)0xCD34, Conversion.byteArrayToShort(src, 0, (short)0x1234, 8, 1));
649 // assertEquals((short)0x5678,Conversion.ByteArrayToShort(src, 7, (short) 0x0123, 8,
650 // 2));
651 }
652
653 /**
654 * Tests {@link Conversion#hexToLong(String, int, long, int, int)}.
655 */
656 @Test
657 public void testHexToLong() {
658 final String src = "CDF1F0C10F12345678";
659 assertEquals(0x0000000000000000L, Conversion.hexToLong(src, 0, 0L, 0, 0));
660 assertEquals(0x000000000000000CL, Conversion.hexToLong(src, 0, 0L, 0, 1));
661 assertEquals(0x000000001C0F1FDCL, Conversion.hexToLong(src, 0, 0L, 0, 8));
662 assertEquals(0x0000000001C0F1FDL, Conversion.hexToLong(src, 1, 0L, 0, 8));
663 assertEquals(
664 0x123456798ABCDEF0L, Conversion.hexToLong(src, 0, 0x123456798ABCDEF0L, 0, 0));
665 assertEquals(
666 0x1234567876BCDEF0L, Conversion.hexToLong(src, 15, 0x123456798ABCDEF0L, 24, 3));
667 }
668
669 /**
670 * Tests {@link Conversion#hexToInt(String, int, int, int, int)}.
671 */
672 @Test
673 public void testHexToInt() {
674 final String src = "CDF1F0C10F12345678";
675 assertEquals(0x00000000, Conversion.hexToInt(src, 0, 0, 0, 0));
676 assertEquals(0x0000000C, Conversion.hexToInt(src, 0, 0, 0, 1));
677 assertEquals(0x1C0F1FDC, Conversion.hexToInt(src, 0, 0, 0, 8));
678 assertEquals(0x01C0F1FD, Conversion.hexToInt(src, 1, 0, 0, 8));
679 assertEquals(0x12345679, Conversion.hexToInt(src, 0, 0x12345679, 0, 0));
680 assertEquals(0x87645679, Conversion.hexToInt(src, 15, 0x12345679, 20, 3));
681 }
682
683 /**
684 * Tests {@link Conversion#hexToShort(String, int, short, int, int)}.
685 */
686 @Test
687 public void testHexToShort() {
688 final String src = "CDF1F0C10F12345678";
689 assertEquals((short)0x0000, Conversion.hexToShort(src, 0, (short)0, 0, 0));
690 assertEquals((short)0x000C, Conversion.hexToShort(src, 0, (short)0, 0, 1));
691 assertEquals((short)0x1FDC, Conversion.hexToShort(src, 0, (short)0, 0, 4));
692 assertEquals((short)0xF1FD, Conversion.hexToShort(src, 1, (short)0, 0, 4));
693 assertEquals((short)0x1234, Conversion.hexToShort(src, 0, (short)0x1234, 0, 0));
694 assertEquals((short)0x8764, Conversion.hexToShort(src, 15, (short)0x1234, 4, 3));
695 }
696
697 /**
698 * Tests {@link Conversion#hexToByte(String, int, byte, int, int)}.
699 */
700 @Test
701 public void testHexToByte() {
702 final String src = "CDF1F0C10F12345678";
703 assertEquals((byte)0x00, Conversion.hexToByte(src, 0, (byte)0, 0, 0));
704 assertEquals((byte)0x0C, Conversion.hexToByte(src, 0, (byte)0, 0, 1));
705 assertEquals((byte)0xDC, Conversion.hexToByte(src, 0, (byte)0, 0, 2));
706 assertEquals((byte)0xFD, Conversion.hexToByte(src, 1, (byte)0, 0, 2));
707 assertEquals((byte)0x34, Conversion.hexToByte(src, 0, (byte)0x34, 0, 0));
708 assertEquals((byte)0x84, Conversion.hexToByte(src, 17, (byte)0x34, 4, 1));
709 }
710
711 /**
712 * Tests {@link Conversion#binaryToLong(boolean[], int, long, int, int)}.
713 */
714 @Test
715 public void testBinaryToLong() {
716 final boolean[] src = new boolean[]{
717 false, false, true, true, true, false, true, true, true, true, true, true, true,
718 false, false, false, true, true, true, true, false, false, false, false, false,
719 false, true, true, true, false, false, false, false, false, false, false, true,
720 true, true, true, true, false, false, false, false, true, false, false, true, true,
721 false, false, false, false, true, false, true, false, true, false, false, true,
722 true, false, true, true, true, false, false, false, false, true};
723 // conversion of "CDF1F0C10F12345678" by HexToBinary
724 assertEquals(0x0000000000000000L, Conversion.binaryToLong(src, 0, 0L, 0, 0));
725 assertEquals(0x000000000000000CL, Conversion.binaryToLong(src, 0, 0L, 0, 1 * 4));
726 assertEquals(0x000000001C0F1FDCL, Conversion.binaryToLong(src, 0, 0L, 0, 8 * 4));
727 assertEquals(0x0000000001C0F1FDL, Conversion.binaryToLong(src, 1 * 4, 0L, 0, 8 * 4));
728 assertEquals(
729 0x123456798ABCDEF0L, Conversion.binaryToLong(src, 0, 0x123456798ABCDEF0L, 0, 0));
730 assertEquals(
731 0x1234567876BCDEF0L,
732 Conversion.binaryToLong(src, 15 * 4, 0x123456798ABCDEF0L, 24, 3 * 4));
733 }
734
735 /**
736 * Tests {@link Conversion#binaryToInt(boolean[], int, int, int, int)}.
737 */
738 @Test
739 public void testBinaryToInt() {
740 final boolean[] src = new boolean[]{
741 false, false, true, true, true, false, true, true, true, true, true, true, true,
742 false, false, false, true, true, true, true, false, false, false, false, false,
743 false, true, true, true, false, false, false, false, false, false, false, true,
744 true, true, true, true, false, false, false, false, true, false, false, true, true,
745 false, false, false, false, true, false, true, false, true, false, false, true,
746 true, false, true, true, true, false, false, false, false, true};
747 // conversion of "CDF1F0C10F12345678" by HexToBinary
748 assertEquals(0x00000000, Conversion.binaryToInt(src, 0 * 4, 0, 0, 0 * 4));
749 assertEquals(0x0000000C, Conversion.binaryToInt(src, 0 * 4, 0, 0, 1 * 4));
750 assertEquals(0x1C0F1FDC, Conversion.binaryToInt(src, 0 * 4, 0, 0, 8 * 4));
751 assertEquals(0x01C0F1FD, Conversion.binaryToInt(src, 1 * 4, 0, 0, 8 * 4));
752 assertEquals(0x12345679, Conversion.binaryToInt(src, 0 * 4, 0x12345679, 0, 0 * 4));
753 assertEquals(0x87645679, Conversion.binaryToInt(src, 15 * 4, 0x12345679, 20, 3 * 4));
754 }
755
756 /**
757 * Tests {@link Conversion#binaryToShort(boolean[], int, short, int, int)}.
758 */
759 @Test
760 public void testBinaryToShort() {
761 final boolean[] src = new boolean[]{
762 false, false, true, true, true, false, true, true, true, true, true, true, true,
763 false, false, false, true, true, true, true, false, false, false, false, false,
764 false, true, true, true, false, false, false, false, false, false, false, true,
765 true, true, true, true, false, false, false, false, true, false, false, true, true,
766 false, false, false, false, true, false, true, false, true, false, false, true,
767 true, false, true, true, true, false, false, false, false, true};
768 // conversion of "CDF1F0C10F12345678" by HexToBinary
769 assertEquals((short)0x0000, Conversion.binaryToShort(src, 0 * 4, (short)0, 0, 0 * 4));
770 assertEquals((short)0x000C, Conversion.binaryToShort(src, 0 * 4, (short)0, 0, 1 * 4));
771 assertEquals((short)0x1FDC, Conversion.binaryToShort(src, 0 * 4, (short)0, 0, 4 * 4));
772 assertEquals((short)0xF1FD, Conversion.binaryToShort(src, 1 * 4, (short)0, 0, 4 * 4));
773 assertEquals(
774 (short)0x1234, Conversion.binaryToShort(src, 0 * 4, (short)0x1234, 0, 0 * 4));
775 assertEquals(
776 (short)0x8764, Conversion.binaryToShort(src, 15 * 4, (short)0x1234, 4, 3 * 4));
777 }
778
779 /**
780 * Tests {@link Conversion#binaryToByte(boolean[], int, byte, int, int)}.
781 */
782 @Test
783 public void testBinaryToByte() {
784 final boolean[] src = new boolean[]{
785 false, false, true, true, true, false, true, true, true, true, true, true, true,
786 false, false, false, true, true, true, true, false, false, false, false, false,
787 false, true, true, true, false, false, false, false, false, false, false, true,
788 true, true, true, true, false, false, false, false, true, false, false, true, true,
789 false, false, false, false, true, false, true, false, true, false, false, true,
790 true, false, true, true, true, false, false, false, false, true};
791 // conversion of "CDF1F0C10F12345678" by HexToBinary
792 assertEquals((byte)0x00, Conversion.binaryToByte(src, 0 * 4, (byte)0, 0, 0 * 4));
793 assertEquals((byte)0x0C, Conversion.binaryToByte(src, 0 * 4, (byte)0, 0, 1 * 4));
794 assertEquals((byte)0xDC, Conversion.binaryToByte(src, 0 * 4, (byte)0, 0, 2 * 4));
795 assertEquals((byte)0xFD, Conversion.binaryToByte(src, 1 * 4, (byte)0, 0, 2 * 4));
796 assertEquals((byte)0x34, Conversion.binaryToByte(src, 0 * 4, (byte)0x34, 0, 0 * 4));
797 assertEquals((byte)0x84, Conversion.binaryToByte(src, 17 * 4, (byte)0x34, 4, 1 * 4));
798 }
799
800 /**
801 * Tests {@link Conversion#longToIntArray(long, int, int[], int, int)}.
802 */
803 @Test
804 public void testLongToIntArray() {
805 assertArrayEquals(
806 new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 0, new int[]{}, 0, 0));
807 assertArrayEquals(
808 new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 100, new int[]{}, 0, 0));
809 assertArrayEquals(
810 new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 0, new int[]{}, 100, 0));
811 assertArrayEquals(
812 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF},
813 Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 0));
814 assertArrayEquals(
815 new int[]{0x90ABCDEF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF},
816 Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 1));
817 assertArrayEquals(
818 new int[]{0x90ABCDEF, 0x12345678, 0xFFFFFFFF, 0xFFFFFFFF},
819 Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 2));
820 // assertArrayEquals(new
821 // int[]{0x90ABCDEF,0x12345678,0x90ABCDEF,0x12345678},Conversion.longToIntArray(0x1234567890ABCDEFL,
822 // 0,new int[]{-1,-1,-1,-1},0,4));//rejected by assertion
823 // assertArrayEquals(new
824 // int[]{0xFFFFFFFF,0x90ABCDEF,0x12345678,0x90ABCDEF},Conversion.longToIntArray(0x1234567890ABCDEFL,
825 // 0,new int[]{-1,-1,-1,-1},1,3));
826 assertArrayEquals(
827 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF, 0x12345678},
828 Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 2, 2));
829 assertArrayEquals(
830 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF, 0xFFFFFFFF},
831 Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 2, 1));
832 assertArrayEquals(
833 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF},
834 Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 3, 1));
835 assertArrayEquals(
836 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x4855E6F7, 0xFFFFFFFF},
837 Conversion.longToIntArray(0x1234567890ABCDEFL, 1, new int[]{-1, -1, -1, -1}, 2, 1));
838 assertArrayEquals(
839 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x242AF37B, 0xFFFFFFFF},
840 Conversion.longToIntArray(0x1234567890ABCDEFL, 2, new int[]{-1, -1, -1, -1}, 2, 1));
841 assertArrayEquals(
842 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x121579BD, 0xFFFFFFFF},
843 Conversion.longToIntArray(0x1234567890ABCDEFL, 3, new int[]{-1, -1, -1, -1}, 2, 1));
844 assertArrayEquals(
845 new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x890ABCDE, 0xFFFFFFFF},
846 Conversion.longToIntArray(0x1234567890ABCDEFL, 4, new int[]{-1, -1, -1, -1}, 2, 1));
847 // assertArrayEquals(new
848 // int[]{0x4855E6F7,0x091A2B3C,0x4855E6F7,0x091A2B3C},Conversion.longToIntArray(0x1234567890ABCDEFL,
849 // 1,new int[]{-1,-1,-1,-1},0,4));//rejected by assertion
850 assertArrayEquals(
851 new int[]{0x091A2B3C},
852 Conversion.longToIntArray(0x1234567890ABCDEFL, 33, new int[]{0}, 0, 1));
853 }
854
855 /**
856 * Tests {@link Conversion#longToShortArray(long, int, short[], int, int)}.
857 */
858 @Test
859 public void testLongToShortArray() {
860 assertArrayEquals(
861 new short[]{},
862 Conversion.longToShortArray(0x0000000000000000L, 0, new short[]{}, 0, 0));
863 assertArrayEquals(
864 new short[]{},
865 Conversion.longToShortArray(0x0000000000000000L, 100, new short[]{}, 0, 0));
866 assertArrayEquals(
867 new short[]{},
868 Conversion.longToShortArray(0x0000000000000000L, 0, new short[]{}, 100, 0));
869 assertArrayEquals(
870 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xFFFF, (short)0xFFFF},
871 Conversion.longToShortArray(
872 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 0));
873 assertArrayEquals(
874 new short[]{(short)0xCDEF, (short)0xFFFF, (short)0xFFFF, (short)0xFFFF},
875 Conversion.longToShortArray(
876 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 1));
877 assertArrayEquals(
878 new short[]{(short)0xCDEF, (short)0x90AB, (short)0xFFFF, (short)0xFFFF},
879 Conversion.longToShortArray(
880 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 2));
881 assertArrayEquals(
882 new short[]{(short)0xCDEF, (short)0x90AB, (short)0x5678, (short)0xFFFF},
883 Conversion.longToShortArray(
884 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 3));
885 assertArrayEquals(
886 new short[]{(short)0xCDEF, (short)0x90AB, (short)0x5678, (short)0x1234},
887 Conversion.longToShortArray(
888 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 4));
889 assertArrayEquals(
890 new short[]{(short)0xFFFF, (short)0xCDEF, (short)0x90AB, (short)0x5678},
891 Conversion.longToShortArray(
892 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 1, 3));
893 assertArrayEquals(
894 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xCDEF, (short)0x90AB},
895 Conversion.longToShortArray(
896 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 2, 2));
897 assertArrayEquals(
898 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xCDEF, (short)0xFFFF},
899 Conversion.longToShortArray(
900 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 2, 1));
901 assertArrayEquals(
902 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xFFFF, (short)0xCDEF},
903 Conversion.longToShortArray(
904 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 3, 1));
905 assertArrayEquals(
906 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xE6F7, (short)0xFFFF},
907 Conversion.longToShortArray(
908 0x1234567890ABCDEFL, 1, new short[]{-1, -1, -1, -1}, 2, 1));
909 assertArrayEquals(
910 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xF37B, (short)0xFFFF},
911 Conversion.longToShortArray(
912 0x1234567890ABCDEFL, 2, new short[]{-1, -1, -1, -1}, 2, 1));
913 assertArrayEquals(
914 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0x79BD, (short)0xFFFF},
915 Conversion.longToShortArray(
916 0x1234567890ABCDEFL, 3, new short[]{-1, -1, -1, -1}, 2, 1));
917 assertArrayEquals(
918 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xBCDE, (short)0xFFFF},
919 Conversion.longToShortArray(
920 0x1234567890ABCDEFL, 4, new short[]{-1, -1, -1, -1}, 2, 1));
921 assertArrayEquals(
922 new short[]{(short)0xE6F7, (short)0x4855, (short)0x2B3C, (short)0x091A},
923 Conversion.longToShortArray(
924 0x1234567890ABCDEFL, 1, new short[]{-1, -1, -1, -1}, 0, 4));
925 assertArrayEquals(
926 new short[]{(short)0x2B3C},
927 Conversion.longToShortArray(0x1234567890ABCDEFL, 33, new short[]{0}, 0, 1));
928 }
929
930 /**
931 * Tests {@link Conversion#intToShortArray(int, int, short[], int, int)}.
932 */
933 @Test
934 public void testIntToShortArray() {
935 assertArrayEquals(
936 new short[]{}, Conversion.intToShortArray(0x00000000, 0, new short[]{}, 0, 0));
937 assertArrayEquals(
938 new short[]{}, Conversion.intToShortArray(0x00000000, 100, new short[]{}, 0, 0));
939 assertArrayEquals(
940 new short[]{}, Conversion.intToShortArray(0x00000000, 0, new short[]{}, 100, 0));
941 assertArrayEquals(
942 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xFFFF, (short)0xFFFF},
943 Conversion.intToShortArray(0x12345678, 0, new short[]{-1, -1, -1, -1}, 0, 0));
944 assertArrayEquals(
945 new short[]{(short)0x5678, (short)0xFFFF, (short)0xFFFF, (short)0xFFFF},
946 Conversion.intToShortArray(0x12345678, 0, new short[]{-1, -1, -1, -1}, 0, 1));
947 assertArrayEquals(
948 new short[]{(short)0x5678, (short)0x1234, (short)0xFFFF, (short)0xFFFF},
949 Conversion.intToShortArray(0x12345678, 0, new short[]{-1, -1, -1, -1}, 0, 2));
950 // assertArrayEquals(new
951 // short[]{(short)0x5678,(short)0x1234,(short)0x5678,(short)0xFFFF},Conversion.intToShortArray(0x12345678,
952 // 0,new short[]{-1,-1,-1,-1},0,3));//rejected by assertion
953 // assertArrayEquals(new
954 // short[]{(short)0x5678,(short)0x1234,(short)0x5678,(short)0x1234},Conversion.intToShortArray(0x12345678,
955 // 0,new short[]{-1,-1,-1,-1},0,4));
956 // assertArrayEquals(new
957 // short[]{(short)0xFFFF,(short)0x5678,(short)0x1234,(short)0x5678},Conversion.intToShortArray(0x12345678,
958 // 0,new short[]{-1,-1,-1,-1},1,3));
959 assertArrayEquals(
960 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0x5678, (short)0x1234},
961 Conversion.intToShortArray(0x12345678, 0, new short[]{-1, -1, -1, -1}, 2, 2));
962 assertArrayEquals(
963 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0x5678, (short)0xFFFF},
964 Conversion.intToShortArray(0x12345678, 0, new short[]{-1, -1, -1, -1}, 2, 1));
965 assertArrayEquals(
966 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0xFFFF, (short)0x5678},
967 Conversion.intToShortArray(0x12345678, 0, new short[]{-1, -1, -1, -1}, 3, 1));
968 assertArrayEquals(
969 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0x2B3C, (short)0xFFFF},
970 Conversion.intToShortArray(0x12345678, 1, new short[]{-1, -1, -1, -1}, 2, 1));
971 assertArrayEquals(
972 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0x159E, (short)0xFFFF},
973 Conversion.intToShortArray(0x12345678, 2, new short[]{-1, -1, -1, -1}, 2, 1));
974 assertArrayEquals(
975 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0x8ACF, (short)0xFFFF},
976 Conversion.intToShortArray(0x12345678, 3, new short[]{-1, -1, -1, -1}, 2, 1));
977 assertArrayEquals(
978 new short[]{(short)0xFFFF, (short)0xFFFF, (short)0x4567, (short)0xFFFF},
979 Conversion.intToShortArray(0x12345678, 4, new short[]{-1, -1, -1, -1}, 2, 1));
980 // assertArrayEquals(new
981 // short[]{(short)0xE6F7,(short)0x4855,(short)0x2B3C,(short)0x091A},Conversion.intToShortArray(0x12345678,
982 // 1,new short[]{-1,-1,-1,-1},0,4));//rejected by assertion
983 // assertArrayEquals(new
984 // short[]{(short)0x2B3C},Conversion.intToShortArray(0x12345678,33,new
985 // short[]{0},0,1));//rejected by assertion
986 assertArrayEquals(
987 new short[]{(short)0x091A},
988 Conversion.intToShortArray(0x12345678, 17, new short[]{0}, 0, 1));
989 }
990
991 /**
992 * Tests {@link Conversion#longToByteArray(long, int, byte[], int, int)}.
993 */
994 @Test
995 public void testLongToByteArray() {
996 assertArrayEquals(
997 new byte[]{},
998 Conversion.longToByteArray(0x0000000000000000L, 0, new byte[]{}, 0, 0));
999 assertArrayEquals(
1000 new byte[]{},
1001 Conversion.longToByteArray(0x0000000000000000L, 100, new byte[]{}, 0, 0));
1002 assertArrayEquals(
1003 new byte[]{},
1004 Conversion.longToByteArray(0x0000000000000000L, 0, new byte[]{}, 100, 0));
1005 assertArrayEquals(
1006 new byte[]{
1007 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1008 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1009 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1010 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 0));
1011 assertArrayEquals(
1012 new byte[]{
1013 (byte)0xEF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1014 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1015 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1016 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1017 assertArrayEquals(
1018 new byte[]{
1019 (byte)0xEF, (byte)0xCD, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1020 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1021 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1022 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 2));
1023 assertArrayEquals(
1024 new byte[]{
1025 (byte)0xEF, (byte)0xCD, (byte)0xAB, (byte)0x90, (byte)0xFF, (byte)0xFF,
1026 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1027 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1028 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 4));
1029 assertArrayEquals(
1030 new byte[]{
1031 (byte)0xEF, (byte)0xCD, (byte)0xAB, (byte)0x90, (byte)0x78, (byte)0x56,
1032 (byte)0x34, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1033 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1034 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 7));
1035 assertArrayEquals(
1036 new byte[]{
1037 (byte)0xEF, (byte)0xCD, (byte)0xAB, (byte)0x90, (byte)0x78, (byte)0x56,
1038 (byte)0x34, (byte)0x12, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1039 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1040 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 8));
1041 assertArrayEquals(
1042 new byte[]{
1043 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xFF, (byte)0xFF,
1044 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1045 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1046 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 1));
1047 assertArrayEquals(
1048 new byte[]{
1049 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xCD, (byte)0xFF,
1050 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1051 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1052 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 2));
1053 assertArrayEquals(
1054 new byte[]{
1055 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xCD, (byte)0xAB,
1056 (byte)0x90, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1057 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1058 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));
1059 assertArrayEquals(
1060 new byte[]{
1061 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xCD, (byte)0xAB,
1062 (byte)0x90, (byte)0x78, (byte)0x56, (byte)0x34, (byte)0xFF},
1063 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1064 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 7));
1065 assertArrayEquals(
1066 new byte[]{
1067 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xCD, (byte)0xAB,
1068 (byte)0x90, (byte)0x78, (byte)0x56, (byte)0x34, (byte)0x12},
1069 Conversion.longToByteArray(0x1234567890ABCDEFL, 0, new byte[]{
1070 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 8));
1071 assertArrayEquals(
1072 new byte[]{
1073 (byte)0xF7, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1074 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1075 Conversion.longToByteArray(0x1234567890ABCDEFL, 1, new byte[]{
1076 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1077 assertArrayEquals(
1078 new byte[]{
1079 (byte)0x7B, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1080 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1081 Conversion.longToByteArray(0x1234567890ABCDEFL, 2, new byte[]{
1082 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1083 assertArrayEquals(
1084 new byte[]{
1085 (byte)0xFF, (byte)0x00, (byte)0xFF, (byte)0x6F, (byte)0x5E, (byte)0x85,
1086 (byte)0xC4, (byte)0xB3, (byte)0xA2, (byte)0x91, (byte)0x00},
1087 Conversion.longToByteArray(0x1234567890ABCDEFL, 5, new byte[]{
1088 -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 8));
1089 // assertArrayEquals(new
1090 // byte[]{(byte)0xFF,(byte)0x00,(byte)0xFF,(byte)0x5E,(byte)0x85,(byte)0xC4,(byte)0xB3,(byte)0xA2,(byte)0x91,(byte)0x00,(byte)0x00},Conversion.longToByteArray(0x1234567890ABCDEFL,13,new
1091 // byte[]{-1, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1},3,8));//rejected by assertion
1092 assertArrayEquals(
1093 new byte[]{
1094 (byte)0xFF, (byte)0x00, (byte)0xFF, (byte)0x5E, (byte)0x85, (byte)0xC4,
1095 (byte)0xB3, (byte)0xA2, (byte)0x91, (byte)0x00, (byte)0xFF},
1096 Conversion.longToByteArray(0x1234567890ABCDEFL, 13, new byte[]{
1097 -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 7));
1098 }
1099
1100 /**
1101 * Tests {@link Conversion#intToByteArray(int, int, byte[], int, int)}.
1102 */
1103 @Test
1104 public void testIntToByteArray() {
1105 assertArrayEquals(
1106 new byte[]{}, Conversion.intToByteArray(0x00000000, 0, new byte[]{}, 0, 0));
1107 assertArrayEquals(
1108 new byte[]{}, Conversion.intToByteArray(0x00000000, 100, new byte[]{}, 0, 0));
1109 assertArrayEquals(
1110 new byte[]{}, Conversion.intToByteArray(0x00000000, 0, new byte[]{}, 100, 0));
1111 assertArrayEquals(
1112 new byte[]{
1113 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1114 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1115 Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
1116 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 0));
1117 assertArrayEquals(
1118 new byte[]{
1119 (byte)0xEF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1120 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1121 Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
1122 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1123 assertArrayEquals(
1124 new byte[]{
1125 (byte)0xEF, (byte)0xCD, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1126 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1127 Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
1128 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 2));
1129 assertArrayEquals(
1130 new byte[]{
1131 (byte)0xEF, (byte)0xCD, (byte)0xAB, (byte)0x90, (byte)0xFF, (byte)0xFF,
1132 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1133 Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
1134 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 4));
1135 assertArrayEquals(
1136 new byte[]{
1137 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xFF, (byte)0xFF,
1138 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1139 Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
1140 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 1));
1141 assertArrayEquals(
1142 new byte[]{
1143 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xCD, (byte)0xFF,
1144 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1145 Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
1146 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 2));
1147 assertArrayEquals(
1148 new byte[]{
1149 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xCD, (byte)0xAB,
1150 (byte)0x90, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1151 Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
1152 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));
1153 assertArrayEquals(
1154 new byte[]{
1155 (byte)0xF7, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1156 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1157 Conversion.intToByteArray(0x90ABCDEF, 1, new byte[]{
1158 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1159 assertArrayEquals(
1160 new byte[]{
1161 (byte)0x7B, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1162 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1163 Conversion.intToByteArray(0x90ABCDEF, 2, new byte[]{
1164 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1165 assertArrayEquals(
1166 new byte[]{
1167 (byte)0xFF, (byte)0x00, (byte)0xFF, (byte)0x6F, (byte)0x5E, (byte)0x85,
1168 (byte)0xFC, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1169 Conversion.intToByteArray(0x90ABCDEF, 5, new byte[]{
1170 -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));
1171 // assertArrayEquals(new
1172 // byte[]{(byte)0xFF,(byte)0x00,(byte)0xFF,(byte)0x5E,(byte)0x85,(byte)0xFC,(byte)0x00,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF},Conversion.intToByteArray(0x90ABCDEF,13,new
1173 // byte[]{-1, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1},3,4));//rejected by assertion
1174 assertArrayEquals(
1175 new byte[]{
1176 (byte)0xFF, (byte)0x00, (byte)0xFF, (byte)0x5E, (byte)0x85, (byte)0xFC,
1177 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF},
1178 Conversion.intToByteArray(0x90ABCDEF, 13, new byte[]{
1179 -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 3));
1180 }
1181
1182 /**
1183 * Tests {@link Conversion#shortToByteArray(short, int, byte[], int, int)}.
1184 */
1185 @Test
1186 public void testShortToByteArray() {
1187 assertArrayEquals(
1188 new byte[]{}, Conversion.shortToByteArray((short)0x0000, 0, new byte[]{}, 0, 0));
1189 assertArrayEquals(
1190 new byte[]{}, Conversion.shortToByteArray((short)0x0000, 100, new byte[]{}, 0, 0));
1191 assertArrayEquals(
1192 new byte[]{}, Conversion.shortToByteArray((short)0x0000, 0, new byte[]{}, 100, 0));
1193 assertArrayEquals(
1194 new byte[]{
1195 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1196 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 0, new byte[]{
1197 -1, -1, -1, -1, -1, -1, -1}, 0, 0));
1198 assertArrayEquals(
1199 new byte[]{
1200 (byte)0xEF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1201 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 0, new byte[]{
1202 -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1203 assertArrayEquals(
1204 new byte[]{
1205 (byte)0xEF, (byte)0xCD, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1206 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 0, new byte[]{
1207 -1, -1, -1, -1, -1, -1, -1}, 0, 2));
1208 assertArrayEquals(
1209 new byte[]{
1210 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xFF, (byte)0xFF,
1211 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 0, new byte[]{
1212 -1, -1, -1, -1, -1, -1, -1}, 3, 1));
1213 assertArrayEquals(
1214 new byte[]{
1215 (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xEF, (byte)0xCD, (byte)0xFF,
1216 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 0, new byte[]{
1217 -1, -1, -1, -1, -1, -1, -1}, 3, 2));
1218 assertArrayEquals(
1219 new byte[]{
1220 (byte)0xF7, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1221 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 1, new byte[]{
1222 -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1223 assertArrayEquals(
1224 new byte[]{
1225 (byte)0x7B, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
1226 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 2, new byte[]{
1227 -1, -1, -1, -1, -1, -1, -1}, 0, 1));
1228 assertArrayEquals(
1229 new byte[]{
1230 (byte)0xFF, (byte)0x00, (byte)0xFF, (byte)0x6F, (byte)0xFE, (byte)0xFF,
1231 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 5, new byte[]{
1232 -1, 0, -1, -1, -1, -1, -1}, 3, 2));
1233 // assertArrayEquals(new
1234 // byte[]{(byte)0xFF,(byte)0x00,(byte)0xFF,(byte)0x5E,(byte)0xFF,(byte)0xFF,(byte)0xFF},Conversion.shortToByteArray((short)0xCDEF,13,new
1235 // byte[]{-1, 0,-1,-1,-1,-1,-1},3,2));//rejected by assertion
1236 assertArrayEquals(
1237 new byte[]{
1238 (byte)0xFF, (byte)0x00, (byte)0xFF, (byte)0xFE, (byte)0xFF, (byte)0xFF,
1239 (byte)0xFF}, Conversion.shortToByteArray((short)0xCDEF, 13, new byte[]{
1240 -1, 0, -1, -1, -1, -1, -1}, 3, 1));
1241 }
1242
1243 /**
1244 * Tests {@link Conversion#longToHex(long, int, String, int, int)}.
1245 */
1246 @Test
1247 public void testLongToHex() {
1248 assertEquals("", Conversion.longToHex(0x0000000000000000L, 0, "", 0, 0));
1249 assertEquals("", Conversion.longToHex(0x0000000000000000L, 100, "", 0, 0));
1250 assertEquals("", Conversion.longToHex(0x0000000000000000L, 0, "", 100, 0));
1251 assertEquals(
1252 "ffffffffffffffffffffffff",
1253 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 0, 0));
1254 assertEquals(
1255 "3fffffffffffffffffffffff",
1256 Conversion.longToHex(0x1234567890ABCDE3L, 0, "ffffffffffffffffffffffff", 0, 1));
1257 assertEquals(
1258 "feffffffffffffffffffffff",
1259 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 0, 2));
1260 assertEquals(
1261 "fedcffffffffffffffffffff",
1262 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 0, 4));
1263 assertEquals(
1264 "fedcba098765432fffffffff",
1265 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 0, 15));
1266 assertEquals(
1267 "fedcba0987654321ffffffff",
1268 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 0, 16));
1269 assertEquals(
1270 "fff3ffffffffffffffffffff",
1271 Conversion.longToHex(0x1234567890ABCDE3L, 0, "ffffffffffffffffffffffff", 3, 1));
1272 assertEquals(
1273 "ffffefffffffffffffffffff",
1274 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 2));
1275 assertEquals(
1276 "ffffedcfffffffffffffffff",
1277 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 4));
1278 assertEquals(
1279 "ffffedcba098765432ffffff",
1280 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 15));
1281 assertEquals(
1282 "ffffedcba0987654321fffff",
1283 Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 16));
1284 assertEquals(
1285 "7fffffffffffffffffffffff",
1286 Conversion.longToHex(0x1234567890ABCDEFL, 1, "ffffffffffffffffffffffff", 0, 1));
1287 assertEquals(
1288 "bfffffffffffffffffffffff",
1289 Conversion.longToHex(0x1234567890ABCDEFL, 2, "ffffffffffffffffffffffff", 0, 1));
1290 assertEquals(
1291 "fffdb975121fca86420fffff",
1292 Conversion.longToHex(0x1234567890ABCDEFL, 3, "ffffffffffffffffffffffff", 3, 16));
1293 // assertEquals("ffffffffffffffffffffffff",Conversion.longToHex(0x1234567890ABCDEFL,4,"ffffffffffffffffffffffff",3,16));//rejected
1294 // by assertion
1295 assertEquals(
1296 "fffedcba0987654321ffffff",
1297 Conversion.longToHex(0x1234567890ABCDEFL, 4, "ffffffffffffffffffffffff", 3, 15));
1298 assertEquals(
1299 "fedcba0987654321", Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 0, 16));
1300 try {
1301 Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 1, 8);
1302 fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
1303 } catch (final StringIndexOutOfBoundsException e) {
1304 // OK
1305 }
1306 }
1307
1308 /**
1309 * Tests {@link Conversion#intToHex(int, int, String, int, int)}.
1310 */
1311 @Test
1312 public void testIntToHex() {
1313 assertEquals("", Conversion.intToHex(0x00000000, 0, "", 0, 0));
1314 assertEquals("", Conversion.intToHex(0x00000000, 100, "", 0, 0));
1315 assertEquals("", Conversion.intToHex(0x00000000, 0, "", 100, 0));
1316 assertEquals(
1317 "ffffffffffffffffffffffff",
1318 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 0));
1319 assertEquals(
1320 "3fffffffffffffffffffffff",
1321 Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 0, 1));
1322 assertEquals(
1323 "feffffffffffffffffffffff",
1324 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 2));
1325 assertEquals(
1326 "fedcffffffffffffffffffff",
1327 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 4));
1328 assertEquals(
1329 "fedcba0fffffffffffffffff",
1330 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 7));
1331 assertEquals(
1332 "fedcba09ffffffffffffffff",
1333 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 8));
1334 assertEquals(
1335 "fff3ffffffffffffffffffff",
1336 Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 3, 1));
1337 assertEquals(
1338 "ffffefffffffffffffffffff",
1339 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 2));
1340 assertEquals(
1341 "ffffedcfffffffffffffffff",
1342 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 4));
1343 assertEquals(
1344 "ffffedcba0ffffffffffffff",
1345 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 7));
1346 assertEquals(
1347 "ffffedcba09fffffffffffff",
1348 Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 8));
1349 assertEquals(
1350 "7fffffffffffffffffffffff",
1351 Conversion.intToHex(0x90ABCDEF, 1, "ffffffffffffffffffffffff", 0, 1));
1352 assertEquals(
1353 "bfffffffffffffffffffffff",
1354 Conversion.intToHex(0x90ABCDEF, 2, "ffffffffffffffffffffffff", 0, 1));
1355 assertEquals(
1356 "fffdb97512ffffffffffffff",
1357 Conversion.intToHex(0x90ABCDEF, 3, "ffffffffffffffffffffffff", 3, 8));
1358 // assertEquals("ffffffffffffffffffffffff",Conversion.intToHex(0x90ABCDEF,
1359 // 4,"ffffffffffffffffffffffff",3,8));//rejected by assertion
1360 assertEquals(
1361 "fffedcba09ffffffffffffff",
1362 Conversion.intToHex(0x90ABCDEF, 4, "ffffffffffffffffffffffff", 3, 7));
1363 assertEquals("fedcba09", Conversion.intToHex(0x90ABCDEF, 0, "", 0, 8));
1364 try {
1365 Conversion.intToHex(0x90ABCDEF, 0, "", 1, 8);
1366 fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
1367 } catch (final StringIndexOutOfBoundsException e) {
1368 // OK
1369 }
1370 }
1371
1372 /**
1373 * Tests {@link Conversion#shortToHex(short, int, String, int, int)}.
1374 */
1375 @Test
1376 public void testShortToHex() {
1377 assertEquals("", Conversion.shortToHex((short)0x0000, 0, "", 0, 0));
1378 assertEquals("", Conversion.shortToHex((short)0x0000, 100, "", 0, 0));
1379 assertEquals("", Conversion.shortToHex((short)0x0000, 0, "", 100, 0));
1380 assertEquals(
1381 "ffffffffffffffffffffffff",
1382 Conversion.shortToHex((short)0xCDEF, 0, "ffffffffffffffffffffffff", 0, 0));
1383 assertEquals(
1384 "3fffffffffffffffffffffff",
1385 Conversion.shortToHex((short)0xCDE3, 0, "ffffffffffffffffffffffff", 0, 1));
1386 assertEquals(
1387 "feffffffffffffffffffffff",
1388 Conversion.shortToHex((short)0xCDEF, 0, "ffffffffffffffffffffffff", 0, 2));
1389 assertEquals(
1390 "fedfffffffffffffffffffff",
1391 Conversion.shortToHex((short)0xCDEF, 0, "ffffffffffffffffffffffff", 0, 3));
1392 assertEquals(
1393 "fedcffffffffffffffffffff",
1394 Conversion.shortToHex((short)0xCDEF, 0, "ffffffffffffffffffffffff", 0, 4));
1395 assertEquals(
1396 "fff3ffffffffffffffffffff",
1397 Conversion.shortToHex((short)0xCDE3, 0, "ffffffffffffffffffffffff", 3, 1));
1398 assertEquals(
1399 "ffffefffffffffffffffffff",
1400 Conversion.shortToHex((short)0xCDEF, 0, "ffffffffffffffffffffffff", 3, 2));
1401 assertEquals(
1402 "7fffffffffffffffffffffff",
1403 Conversion.shortToHex((short)0xCDEF, 1, "ffffffffffffffffffffffff", 0, 1));
1404 assertEquals(
1405 "bfffffffffffffffffffffff",
1406 Conversion.shortToHex((short)0xCDEF, 2, "ffffffffffffffffffffffff", 0, 1));
1407 assertEquals(
1408 "fffdb9ffffffffffffffffff",
1409 Conversion.shortToHex((short)0xCDEF, 3, "ffffffffffffffffffffffff", 3, 4));
1410 // assertEquals("ffffffffffffffffffffffff",Conversion.shortToHex((short)0xCDEF,
1411 // 4,"ffffffffffffffffffffffff",3,4));//rejected by assertion
1412 assertEquals(
1413 "fffedcffffffffffffffffff",
1414 Conversion.shortToHex((short)0xCDEF, 4, "ffffffffffffffffffffffff", 3, 3));
1415 assertEquals("fedc", Conversion.shortToHex((short)0xCDEF, 0, "", 0, 4));
1416 try {
1417 Conversion.shortToHex((short)0xCDEF, 0, "", 1, 4);
1418 fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
1419 } catch (final StringIndexOutOfBoundsException e) {
1420 // OK
1421 }
1422 }
1423
1424 /**
1425 * Tests {@link Conversion#byteToHex(byte, int, String, int, int)}.
1426 */
1427 @Test
1428 public void testByteToHex() {
1429 assertEquals("", Conversion.byteToHex((byte)0x00, 0, "", 0, 0));
1430 assertEquals("", Conversion.byteToHex((byte)0x00, 100, "", 0, 0));
1431 assertEquals("", Conversion.byteToHex((byte)0x00, 0, "", 100, 0));
1432 assertEquals("00000", Conversion.byteToHex((byte)0xEF, 0, "00000", 0, 0));
1433 assertEquals("f0000", Conversion.byteToHex((byte)0xEF, 0, "00000", 0, 1));
1434 assertEquals("fe000", Conversion.byteToHex((byte)0xEF, 0, "00000", 0, 2));
1435 assertEquals("000f0", Conversion.byteToHex((byte)0xEF, 0, "00000", 3, 1));
1436 assertEquals("000fe", Conversion.byteToHex((byte)0xEF, 0, "00000", 3, 2));
1437 assertEquals("70000", Conversion.byteToHex((byte)0xEF, 1, "00000", 0, 1));
1438 assertEquals("b0000", Conversion.byteToHex((byte)0xEF, 2, "00000", 0, 1));
1439 assertEquals("000df", Conversion.byteToHex((byte)0xEF, 3, "00000", 3, 2));
1440 // assertEquals("00000",Conversion.byteToHex((byte)0xEF, 4,"00000",3,2));//rejected by
1441 // assertion
1442 assertEquals("000e0", Conversion.byteToHex((byte)0xEF, 4, "00000", 3, 1));
1443 assertEquals("fe", Conversion.byteToHex((byte)0xEF, 0, "", 0, 2));
1444 try {
1445 Conversion.byteToHex((byte)0xEF, 0, "", 1, 2);
1446 fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
1447 } catch (final StringIndexOutOfBoundsException e) {
1448 // OK
1449 }
1450 }
1451
1452 /**
1453 * Tests {@link Conversion#longToBinary(long, int, boolean[], int, int)}.
1454 */
1455 @Test
1456 public void testLongToBinary() {
1457 assertBinaryEquals(
1458 new boolean[]{},
1459 Conversion.longToBinary(0x0000000000000000L, 0, new boolean[]{}, 0, 0));
1460 assertBinaryEquals(
1461 new boolean[]{},
1462 Conversion.longToBinary(0x0000000000000000L, 100, new boolean[]{}, 0, 0));
1463 assertBinaryEquals(
1464 new boolean[]{},
1465 Conversion.longToBinary(0x0000000000000000L, 0, new boolean[]{}, 100, 0));
1466 assertBinaryEquals(
1467 new boolean[69],
1468 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 0));
1469
1470 assertBinaryEquals(
1471 new boolean[]{
1472 true, false, false, false, false, false, false, false, false, false, false,
1473 false, false, false, false, false, false, false, false, false, false, false,
1474 false, false, false, false, false, false, false, false, false, false, false,
1475 false, false, false, false, false, false, false, false, false, false, false,
1476 false, false, false, false, false, false, false, false, false, false, false,
1477 false, false, false, false, false, false, false, false, false, false, false,
1478 false, false, false},
1479 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 1));
1480 assertBinaryEquals(
1481 new boolean[]{
1482 true, true, false, false, false, false, false, false, false, false, false,
1483 false, false, false, false, false, false, false, false, false, false, false,
1484 false, false, false, false, false, false, false, false, false, false, false,
1485 false, false, false, false, false, false, false, false, false, false, false,
1486 false, false, false, false, false, false, false, false, false, false, false,
1487 false, false, false, false, false, false, false, false, false, false, false,
1488 false, false, false},
1489 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 2));
1490 assertBinaryEquals(
1491 new boolean[]{
1492 true, true, true, false, false, false, false, false, false, false, false,
1493 false, false, false, false, false, false, false, false, false, false, false,
1494 false, false, false, false, false, false, false, false, false, false, false,
1495 false, false, false, false, false, false, false, false, false, false, false,
1496 false, false, false, false, false, false, false, false, false, false, false,
1497 false, false, false, false, false, false, false, false, false, false, false,
1498 false, false, false},
1499 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 3));
1500 assertBinaryEquals(
1501 new boolean[]{
1502 true, true, true, true, false, true, true, true, true, false, true, true,
1503 false, false, true, true, true, true, false, true, false, true, false, true,
1504 false, false, false, false, true, false, false, true, false, false, false,
1505 true, true, true, true, false, false, true, true, false, true, false, true,
1506 false, false, false, true, false, true, true, false, false, false, true, false,
1507 false, true, false, false, false, false, false, false, false, false},
1508 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 63));
1509 assertBinaryEquals(
1510 new boolean[]{
1511 true, true, true, true, false, true, true, true, true, false, true, true,
1512 false, false, true, true, true, true, false, true, false, true, false, true,
1513 false, false, false, false, true, false, false, true, false, false, false,
1514 true, true, true, true, false, false, true, true, false, true, false, true,
1515 false, false, false, true, false, true, true, false, false, false, true, false,
1516 false, true, false, false, false, false, false, false, false, false},
1517 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 64));
1518 assertBinaryEquals(
1519 new boolean[]{
1520 false, false, true, false, false, false, false, false, false, false, false,
1521 false, false, false, false, false, false, false, false, false, false, false,
1522 false, false, false, false, false, false, false, false, false, false, false,
1523 false, false, false, false, false, false, false, false, false, false, false,
1524 false, false, false, false, false, false, false, false, false, false, false,
1525 false, false, false, false, false, false, false, false, false, false, false,
1526 false, false, false},
1527 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 2, 1));
1528 assertBinaryEquals(
1529 new boolean[]{
1530 false, false, true, true, true, true, false, true, true, true, true, false,
1531 true, true, false, false, true, true, true, true, false, true, false, true,
1532 false, true, false, false, false, false, true, false, false, true, false,
1533 false, false, true, true, true, true, false, false, true, true, false, true,
1534 false, true, false, false, false, true, false, true, true, false, false, false,
1535 true, false, false, true, false, false, false, false, false, false},
1536 Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 2, 64));
1537 assertBinaryEquals(
1538 new boolean[]{
1539 true, true, true, false, true, true, true, true, false, true, true, false,
1540 false, true, true, true, true, false, true, false, true, false, true, false,
1541 false, false, false, true, false, false, true, false, false, false, true, true,
1542 true, true, false, false, true, true, false, true, false, true, false, false,
1543 false, true, false, true, true, false, false, false, true, false, false, true,
1544 false, false, false, false, false, false, false, false, false},
1545 Conversion.longToBinary(0x1234567890ABCDEFL, 1, new boolean[69], 0, 63));
1546 assertBinaryEquals(
1547 new boolean[]{
1548 true, true, false, true, true, true, true, false, true, true, false, false,
1549 true, true, true, true, false, true, false, true, false, true, false, false,
1550 false, false, true, false, false, true, false, false, false, true, true, true,
1551 true, false, false, true, true, false, true, false, true, false, false, false,
1552 true, false, true, true, false, false, false, true, false, false, true, false,
1553 false, false, false, false, false, false, false, false, false},
1554 Conversion.longToBinary(0x1234567890ABCDEFL, 2, new boolean[69], 0, 62));
1555
1556 // assertBinaryEquals(new boolean[]{false,false,false, true, true, false, true, true,
1557 // true, true, false, true, true, false, false, true, true, true, true, false, true,
1558 // false, true, false, true, false, false, false, false, true, false, false, true,
1559 // false, false, false, true, true, true, true, false, false, true, true, false, true,
1560 // false, true, false, false, false, true, false, true, true, false, false, false, true,
1561 // false, false, true, false, false, false
1562 // ,false,false,false,false},Conversion.longToBinary(0x1234567890ABCDEFL, 2,new
1563 // boolean[69], 3, 63));//rejected by assertion
1564 assertBinaryEquals(
1565 new boolean[]{
1566 false, false, false, true, true, false, true, true, true, true, false, true,
1567 true, false, false, true, true, true, true, false, true, false, true, false,
1568 true, false, false, false, false, true, false, false, true, false, false,
1569 false, true, true, true, true, false, false, true, true, false, true, false,
1570 true, false, false, false, true, false, true, true, false, false, false, true,
1571 false, false, true, false, false, false, false, false, false, false},
1572 Conversion.longToBinary(0x1234567890ABCDEFL, 2, new boolean[69], 3, 62));
1573 }
1574
1575 /**
1576 * Tests {@link Conversion#intToBinary(int, int, boolean[], int, int)}.
1577 */
1578 @Test
1579 public void testIntToBinary() {
1580 assertBinaryEquals(
1581 new boolean[]{}, Conversion.intToBinary(0x00000000, 0, new boolean[]{}, 0, 0));
1582 assertBinaryEquals(
1583 new boolean[]{}, Conversion.intToBinary(0x00000000, 100, new boolean[]{}, 0, 0));
1584 assertBinaryEquals(
1585 new boolean[]{}, Conversion.intToBinary(0x00000000, 0, new boolean[]{}, 100, 0));
1586 assertBinaryEquals(
1587 new boolean[69], Conversion.intToBinary(0x90ABCDEF, 0, new boolean[69], 0, 0));
1588 assertBinaryEquals(new boolean[]{
1589 true, false, false, false, false, false, false, false, false, false, false, false,
1590 false, false, false, false, false, false, false, false, false, false, false, false,
1591 false, false, false, false, false, false, false, false, false, false, false, false,
1592 false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 1));
1593 assertBinaryEquals(new boolean[]{
1594 true, true, false, false, false, false, false, false, false, false, false, false,
1595 false, false, false, false, false, false, false, false, false, false, false, false,
1596 false, false, false, false, false, false, false, false, false, false, false, false,
1597 false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 2));
1598 assertBinaryEquals(new boolean[]{
1599 true, true, true, false, false, false, false, false, false, false, false, false,
1600 false, false, false, false, false, false, false, false, false, false, false, false,
1601 false, false, false, false, false, false, false, false, false, false, false, false,
1602 false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 3));
1603 assertBinaryEquals(
1604 new boolean[]{
1605 true, true, true, true, false, true, true, true, true, false, true, true,
1606 false, false, true, true, true, true, false, true, false, true, false, true,
1607 false, false, false, false, true, false, false, false, false, false, false,
1608 false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 31));
1609 assertBinaryEquals(
1610 new boolean[]{
1611 true, true, true, true, false, true, true, true, true, false, true, true,
1612 false, false, true, true, true, true, false, true, false, true, false, true,
1613 false, false, false, false, true, false, false, true, false, false, false,
1614 false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 32));
1615 assertBinaryEquals(new boolean[]{
1616 false, false, true, false, false, false, false, false, false, false, false, false,
1617 false, false, false, false, false, false, false, false, false, false, false, false,
1618 false, false, false, false, false, false, false, false, false, false, false, false,
1619 false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 2, 1));
1620 assertBinaryEquals(
1621 new boolean[]{
1622 false, false, true, true, true, true, false, true, true, true, true, false,
1623 true, true, false, false, true, true, true, true, false, true, false, true,
1624 false, true, false, false, false, false, true, false, false, true, false,
1625 false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 2, 32));
1626 assertBinaryEquals(
1627 new boolean[]{
1628 true, true, true, false, true, true, true, true, false, true, true, false,
1629 false, true, true, true, true, false, true, false, true, false, true, false,
1630 false, false, false, true, false, false, true, false, false, false, false,
1631 false, false}, Conversion.intToBinary(0x90ABCDEF, 1, new boolean[37], 0, 31));
1632 assertBinaryEquals(
1633 new boolean[]{
1634 true, true, false, true, true, true, true, false, true, true, false, false,
1635 true, true, true, true, false, true, false, true, false, true, false, false,
1636 false, false, true, false, false, true, false, false, false, false, false,
1637 false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37], 0, 30));
1638 // assertBinaryEquals(new boolean[]{false, false, false, true, true, false, true,
1639 // true,
1640 // true, true, false, true, true, false, false, true, true, true, true, false, true,
1641 // false, true, false, true, false, false, false, false, true, false, false, false,
1642 // false, false, false, false},Conversion.intToBinary(0x90ABCDEF, 2,new boolean[37],
1643 // 3,31));//rejected by assertion
1644 assertBinaryEquals(
1645 new boolean[]{
1646 false, false, false, true, true, false, true, true, true, true, false, true,
1647 true, false, false, true, true, true, true, false, true, false, true, false,
1648 true, false, false, false, false, true, false, false, true, false, false,
1649 false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37], 3, 30));
1650 }
1651
1652 /**
1653 * Tests {@link Conversion#shortToBinary(short, int, boolean[], int, int)}.
1654 */
1655 @Test
1656 public void testShortToBinary() {
1657 assertBinaryEquals(
1658 new boolean[]{}, Conversion.shortToBinary((short)0x0000, 0, new boolean[]{}, 0, 0));
1659 assertBinaryEquals(
1660 new boolean[]{},
1661 Conversion.shortToBinary((short)0x0000, 100, new boolean[]{}, 0, 0));
1662 assertBinaryEquals(
1663 new boolean[]{},
1664 Conversion.shortToBinary((short)0x0000, 0, new boolean[]{}, 100, 0));
1665 assertBinaryEquals(
1666 new boolean[69], Conversion.shortToBinary((short)0xCDEF, 0, new boolean[69], 0, 0));
1667 assertBinaryEquals(
1668 new boolean[]{
1669 true, false, false, false, false, false, false, false, false, false, false,
1670 false, false, false, false, false, false, false, false, false, false},
1671 Conversion.shortToBinary((short)0xCDEF, 0, new boolean[21], 0, 1));
1672 assertBinaryEquals(
1673 new boolean[]{
1674 true, true, false, false, false, false, false, false, false, false, false,
1675 false, false, false, false, false, false, false, false, false, false},
1676 Conversion.shortToBinary((short)0xCDEF, 0, new boolean[21], 0, 2));
1677 assertBinaryEquals(
1678 new boolean[]{
1679 true, true, true, false, false, false, false, false, false, false, false,
1680 false, false, false, false, false, false, false, false, false, false},
1681 Conversion.shortToBinary((short)0xCDEF, 0, new boolean[21], 0, 3));
1682 assertBinaryEquals(
1683 new boolean[]{
1684 true, true, true, true, false, true, true, true, true, false, true, true,
1685 false, false, true, false, false, false, false, false, false},
1686 Conversion.shortToBinary((short)0xCDEF, 0, new boolean[21], 0, 15));
1687 assertBinaryEquals(
1688 new boolean[]{
1689 true, true, true, true, false, true, true, true, true, false, true, true,
1690 false, false, true, true, false, false, false, false, false},
1691 Conversion.shortToBinary((short)0xCDEF, 0, new boolean[21], 0, 16));
1692 assertBinaryEquals(
1693 new boolean[]{
1694 false, false, true, false, false, false, false, false, false, false, false,
1695 false, false, false, false, false, false, false, false, false, false},
1696 Conversion.shortToBinary((short)0xCDEF, 0, new boolean[21], 2, 1));
1697 assertBinaryEquals(
1698 new boolean[]{
1699 false, false, true, true, true, true, false, true, true, true, true, false,
1700 true, true, false, false, true, true, false, false, false},
1701 Conversion.shortToBinary((short)0xCDEF, 0, new boolean[21], 2, 16));
1702 assertBinaryEquals(
1703 new boolean[]{
1704 true, true, true, false, true, true, true, true, false, true, true, false,
1705 false, true, true, false, false, false, false, false, false},
1706 Conversion.shortToBinary((short)0xCDEF, 1, new boolean[21], 0, 15));
1707 assertBinaryEquals(
1708 new boolean[]{
1709 true, true, false, true, true, true, true, false, true, true, false, false,
1710 true, true, false, false, false, false, false, false, false},
1711 Conversion.shortToBinary((short)0xCDEF, 2, new boolean[21], 0, 14));
1712 // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true, true,
1713 // true, true, false, true, true, false, false, true, false, false, false, false,
1714 // false},Conversion.shortToBinary((short)0xCDEF, 2,new boolean[21],
1715 // 3,15));//rejected by
1716 // assertion
1717 assertBinaryEquals(
1718 new boolean[]{
1719 false, false, false, true, true, false, true, true, true, true, false, true,
1720 true, false, false, true, true, false, false, false, false},
1721 Conversion.shortToBinary((short)0xCDEF, 2, new boolean[21], 3, 14));
1722 }
1723
1724 /**
1725 * Tests {@link Conversion#byteToBinary(byte, int, boolean[], int, int)}.
1726 */
1727 @Test
1728 public void testByteToBinary() {
1729 assertBinaryEquals(
1730 new boolean[]{}, Conversion.byteToBinary((byte)0x00, 0, new boolean[]{}, 0, 0));
1731 assertBinaryEquals(
1732 new boolean[]{}, Conversion.byteToBinary((byte)0x00, 100, new boolean[]{}, 0, 0));
1733 assertBinaryEquals(
1734 new boolean[]{}, Conversion.byteToBinary((byte)0x00, 0, new boolean[]{}, 100, 0));
1735 assertBinaryEquals(
1736 new boolean[69], Conversion.byteToBinary((byte)0xEF, 0, new boolean[69], 0, 0));
1737 assertBinaryEquals(new boolean[]{
1738 true, false, false, false, false, false, false, false, false, false, false, false,
1739 false}, Conversion.byteToBinary((byte)0x95, 0, new boolean[13], 0, 1));
1740 assertBinaryEquals(new boolean[]{
1741 true, false, false, false, false, false, false, false, false, false, false, false,
1742 false}, Conversion.byteToBinary((byte)0x95, 0, new boolean[13], 0, 2));
1743 assertBinaryEquals(new boolean[]{
1744 true, false, true, false, false, false, false, false, false, false, false, false,
1745 false}, Conversion.byteToBinary((byte)0x95, 0, new boolean[13], 0, 3));
1746 assertBinaryEquals(new boolean[]{
1747 true, false, true, false, true, false, false, false, false, false, false, false,
1748 false}, Conversion.byteToBinary((byte)0x95, 0, new boolean[13], 0, 7));
1749 assertBinaryEquals(new boolean[]{
1750 true, false, true, false, true, false, false, true, false, false, false, false,
1751 false}, Conversion.byteToBinary((byte)0x95, 0, new boolean[13], 0, 8));
1752 assertBinaryEquals(new boolean[]{
1753 false, false, true, false, false, false, false, false, false, false, false, false,
1754 false}, Conversion.byteToBinary((byte)0x95, 0, new boolean[13], 2, 1));
1755 assertBinaryEquals(new boolean[]{
1756 false, false, true, false, true, false, true, false, false, true, false, false,
1757 false}, Conversion.byteToBinary((byte)0x95, 0, new boolean[13], 2, 8));
1758 assertBinaryEquals(new boolean[]{
1759 false, true, false, true, false, false, true, false, false, false, false, false,
1760 false}, Conversion.byteToBinary((byte)0x95, 1, new boolean[13], 0, 7));
1761 assertBinaryEquals(new boolean[]{
1762 true, false, true, false, false, true, false, false, false, false, false, false,
1763 false}, Conversion.byteToBinary((byte)0x95, 2, new boolean[13], 0, 6));
1764 // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true, true,
1765 // false, false, false, false, false},Conversion.byteToBinary((byte)0x95, 2,new
1766 // boolean[13], 3, 7));//rejected by assertion
1767 assertBinaryEquals(new boolean[]{
1768 false, false, false, true, false, true, false, false, true, false, false, false,
1769 false}, Conversion.byteToBinary((byte)0x95, 2, new boolean[13], 3, 6));
1770 }
1771
1772 /**
1773 * Tests {@link Conversion#uuidToByteArray(UUID, byte[], int, int)}.
1774 */
1775 @Test
1776 public void testUuidToByteArray() {
1777 assertArrayEquals(new byte[]{
1778 (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
1779 (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
1780 (byte)0xff, (byte)0xff}, Conversion.uuidToByteArray(new UUID(
1781 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL), new byte[16], 0, 16));
1782 assertArrayEquals(new byte[]{
1783 (byte)0x88, (byte)0x99, (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd, (byte)0xee,
1784 (byte)0xff, (byte)0x00, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55,
1785 (byte)0x66, (byte)0x77}, Conversion.uuidToByteArray(new UUID(
1786 0xFFEEDDCCBBAA9988L, 0x7766554433221100L), new byte[16], 0, 16));
1787 assertArrayEquals(new byte[]{
1788 (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x88, (byte)0x99, (byte)0xaa,
1789 (byte)0xbb, (byte)0xcc, (byte)0xdd, (byte)0xee, (byte)0xff, (byte)0x00, (byte)0x00,
1790 (byte)0x00, (byte)0x00}, Conversion.uuidToByteArray(new UUID(
1791 0xFFEEDDCCBBAA9988L, 0x7766554433221100L), new byte[16], 4, 8));
1792 assertArrayEquals(new byte[]{
1793 (byte)0x00, (byte)0x00, (byte)0x88, (byte)0x99, (byte)0xaa, (byte)0xbb, (byte)0xcc,
1794 (byte)0xdd, (byte)0xee, (byte)0xff, (byte)0x00, (byte)0x11, (byte)0x22, (byte)0x33,
1795 (byte)0x00, (byte)0x00}, Conversion.uuidToByteArray(new UUID(
1796 0xFFEEDDCCBBAA9988L, 0x7766554433221100L), new byte[16], 2, 12));
1797 }
1798
1799 /**
1800 * Tests {@link Conversion#byteArrayToUuid(byte[], int)}.
1801 */
1802 @Test
1803 public void testByteArrayToUuid() {
1804 assertEquals(
1805 new UUID(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL),
1806 Conversion.byteArrayToUuid(new byte[]{
1807 (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
1808 (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
1809 (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}, 0));
1810 assertEquals(
1811 new UUID(0xFFEEDDCCBBAA9988L, 0x7766554433221100L),
1812 Conversion.byteArrayToUuid(new byte[]{
1813 (byte)0x88, (byte)0x99, (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd,
1814 (byte)0xee, (byte)0xff, (byte)0x00, (byte)0x11, (byte)0x22, (byte)0x33,
1815 (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77}, 0));
1816 assertEquals(
1817 new UUID(0xFFEEDDCCBBAA9988L, 0x7766554433221100L),
1818 Conversion.byteArrayToUuid(new byte[]{
1819 0, 0, (byte)0x88, (byte)0x99, (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd,
1820 (byte)0xee, (byte)0xff, (byte)0x00, (byte)0x11, (byte)0x22, (byte)0x33,
1821 (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77}, 2));
1822 }
1823 }
1717 */
1818 package org.apache.commons.lang3;
1919
20 import static org.junit.Assert.*;
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertTrue;
2123
2224 import java.util.ArrayList;
25 import java.util.Arrays;
2326 import java.util.EnumSet;
2427 import java.util.List;
2528 import java.util.Map;
2629
30 import org.junit.Assert;
2731 import org.junit.Test;
2832
2933 /**
3034 *
31 * @version $Id: EnumUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
35 * @version $Id: EnumUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3236 */
3337 public class EnumUtilsTest {
3438
4044
4145 @Test
4246 public void test_getEnumMap() {
43 Map<String, Traffic> test = EnumUtils.getEnumMap(Traffic.class);
47 final Map<String, Traffic> test = EnumUtils.getEnumMap(Traffic.class);
4448 assertEquals( "getEnumMap not created correctly", "{RED=RED, AMBER=AMBER, GREEN=GREEN}", test.toString());
4549 assertEquals(3, test.size());
4650 assertTrue(test.containsKey("RED"));
5458
5559 @Test
5660 public void test_getEnumList() {
57 List<Traffic> test = EnumUtils.getEnumList(Traffic.class);
61 final List<Traffic> test = EnumUtils.getEnumList(Traffic.class);
5862 assertEquals(3, test.size());
5963 assertEquals(Traffic.RED, test.get(0));
6064 assertEquals(Traffic.AMBER, test.get(1));
9599 }
96100
97101 @Test(expected=NullPointerException.class)
102 public void test_generateBitVectors_nullClass() {
103 EnumUtils.generateBitVectors(null, EnumSet.of(Traffic.RED));
104 }
105
106 @Test(expected=NullPointerException.class)
98107 public void test_generateBitVector_nullIterable() {
99 EnumUtils.generateBitVector(null, (Iterable<Traffic>) null);
100 }
101
108 EnumUtils.generateBitVector(Traffic.class, (Iterable<Traffic>) null);
109 }
110
111 @Test(expected=NullPointerException.class)
112 public void test_generateBitVectors_nullIterable() {
113 EnumUtils.generateBitVectors(null, (Iterable<Traffic>) null);
114 }
115
116 @Test(expected=IllegalArgumentException.class)
117 public void test_generateBitVector_nullElement() {
118 EnumUtils.generateBitVector(Traffic.class, Arrays.asList(Traffic.RED, null));
119 }
120
121 @Test(expected=IllegalArgumentException.class)
122 public void test_generateBitVectors_nullElement() {
123 EnumUtils.generateBitVectors(Traffic.class, Arrays.asList(Traffic.RED, null));
124 }
125
102126 @Test(expected=NullPointerException.class)
103127 public void test_generateBitVector_nullClassWithArray() {
104128 EnumUtils.generateBitVector(null, Traffic.RED);
105129 }
106130
107131 @Test(expected=NullPointerException.class)
132 public void test_generateBitVectors_nullClassWithArray() {
133 EnumUtils.generateBitVectors(null, Traffic.RED);
134 }
135
136 @Test(expected=NullPointerException.class)
108137 public void test_generateBitVector_nullArray() {
109 EnumUtils.generateBitVector(null, (Traffic[]) null);
110 }
111
138 EnumUtils.generateBitVector(Traffic.class, (Traffic[]) null);
139 }
140
141 @Test(expected=NullPointerException.class)
142 public void test_generateBitVectors_nullArray() {
143 EnumUtils.generateBitVectors(Traffic.class, (Traffic[]) null);
144 }
145
146 @Test(expected=IllegalArgumentException.class)
147 public void test_generateBitVector_nullArrayElement() {
148 EnumUtils.generateBitVector(Traffic.class, Traffic.RED, null);
149 }
150
151 @Test(expected=IllegalArgumentException.class)
152 public void test_generateBitVectors_nullArrayElement() {
153 EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, null);
154 }
155
112156 @Test(expected=IllegalArgumentException.class)
113157 public void test_generateBitVector_longClass() {
114158 EnumUtils.generateBitVector(TooMany.class, EnumSet.of(TooMany.A1));
123167 @Test(expected=IllegalArgumentException.class)
124168 public void test_generateBitVector_nonEnumClass() {
125169 @SuppressWarnings("rawtypes")
170 final
126171 Class rawType = Object.class;
127172 @SuppressWarnings("rawtypes")
173 final
128174 List rawList = new ArrayList();
129175 EnumUtils.generateBitVector(rawType, rawList);
130176 }
131177
132178 @SuppressWarnings("unchecked")
133179 @Test(expected=IllegalArgumentException.class)
180 public void test_generateBitVectors_nonEnumClass() {
181 @SuppressWarnings("rawtypes")
182 final
183 Class rawType = Object.class;
184 @SuppressWarnings("rawtypes")
185 final
186 List rawList = new ArrayList();
187 EnumUtils.generateBitVectors(rawType, rawList);
188 }
189
190 @SuppressWarnings("unchecked")
191 @Test(expected=IllegalArgumentException.class)
134192 public void test_generateBitVector_nonEnumClassWithArray() {
135193 @SuppressWarnings("rawtypes")
194 final
136195 Class rawType = Object.class;
137196 EnumUtils.generateBitVector(rawType);
197 }
198
199 @SuppressWarnings("unchecked")
200 @Test(expected=IllegalArgumentException.class)
201 public void test_generateBitVectors_nonEnumClassWithArray() {
202 @SuppressWarnings("rawtypes")
203 final
204 Class rawType = Object.class;
205 EnumUtils.generateBitVectors(rawType);
138206 }
139207
140208 @Test
147215 assertEquals(5L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.GREEN)));
148216 assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)));
149217 assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)));
218 }
219
220 @Test
221 public void test_generateBitVectors() {
222 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.noneOf(Traffic.class)), 0L);
223 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED)), 1L);
224 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.AMBER)), 2L);
225 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.GREEN)), 4L);
226 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER)), 3L);
227 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.GREEN)), 5L);
228 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)), 6L);
229 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)), 7L);
150230 }
151231
152232 @Test
163243 assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN));
164244 }
165245
246 @Test
247 public void test_generateBitVectorsFromArray() {
248 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class), 0L);
249 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED), 1L);
250 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.AMBER), 2L);
251 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.GREEN), 4L);
252 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER), 3L);
253 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.GREEN), 5L);
254 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.AMBER, Traffic.GREEN), 6L);
255 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN), 7L);
256 //gracefully handles duplicates:
257 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN), 7L);
258 }
259
260 private void assertArrayEquals(final long[] actual, final long... expected) {
261 Assert.assertArrayEquals(expected, actual);
262 }
263
166264 @Test(expected=NullPointerException.class)
167265 public void test_processBitVector_nullClass() {
168266 final Class<Traffic> empty = null;
169267 EnumUtils.processBitVector(empty, 0L);
170268 }
171269
172 @Test(expected=IllegalArgumentException.class)
173 public void test_processBitVector_longClass() {
174 EnumUtils.processBitVector(TooMany.class, 0L);
270 @Test(expected=NullPointerException.class)
271 public void test_processBitVectors_nullClass() {
272 final Class<Traffic> empty = null;
273 EnumUtils.processBitVectors(empty, 0L);
175274 }
176275
177276 @Test
185284 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 6L));
186285 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 7L));
187286 }
287
288 @Test
289 public void test_processBitVectors() {
290 assertEquals(EnumSet.noneOf(Traffic.class), EnumUtils.processBitVectors(Traffic.class, 0L));
291 assertEquals(EnumSet.of(Traffic.RED), EnumUtils.processBitVectors(Traffic.class, 1L));
292 assertEquals(EnumSet.of(Traffic.AMBER), EnumUtils.processBitVectors(Traffic.class, 2L));
293 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER), EnumUtils.processBitVectors(Traffic.class, 3L));
294 assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 4L));
295 assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 5L));
296 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 6L));
297 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 7L));
298
299 assertEquals(EnumSet.noneOf(Traffic.class), EnumUtils.processBitVectors(Traffic.class, 0L, 0L));
300 assertEquals(EnumSet.of(Traffic.RED), EnumUtils.processBitVectors(Traffic.class, 0L, 1L));
301 assertEquals(EnumSet.of(Traffic.AMBER), EnumUtils.processBitVectors(Traffic.class, 0L, 2L));
302 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER), EnumUtils.processBitVectors(Traffic.class, 0L, 3L));
303 assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 4L));
304 assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 5L));
305 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 6L));
306 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 7L));
307
308 // demonstrate tolerance of irrelevant high-order digits:
309 assertEquals(EnumSet.noneOf(Traffic.class), EnumUtils.processBitVectors(Traffic.class, 666L, 0L));
310 assertEquals(EnumSet.of(Traffic.RED), EnumUtils.processBitVectors(Traffic.class, 666L, 1L));
311 assertEquals(EnumSet.of(Traffic.AMBER), EnumUtils.processBitVectors(Traffic.class, 666L, 2L));
312 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER), EnumUtils.processBitVectors(Traffic.class, 666L, 3L));
313 assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 4L));
314 assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 5L));
315 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 6L));
316 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 7L));
317 }
318
319 @Test(expected=IllegalArgumentException.class)
320 public void test_processBitVector_longClass() {
321 EnumUtils.processBitVector(TooMany.class, 0L);
322 }
323
324 public void test_processBitVectors_longClass() {
325 assertEquals(EnumSet.noneOf(TooMany.class), EnumUtils.processBitVectors(TooMany.class, 0L));
326 assertEquals(EnumSet.of(TooMany.A), EnumUtils.processBitVectors(TooMany.class, 1L));
327 assertEquals(EnumSet.of(TooMany.B), EnumUtils.processBitVectors(TooMany.class, 2L));
328 assertEquals(EnumSet.of(TooMany.A, TooMany.B), EnumUtils.processBitVectors(TooMany.class, 3L));
329 assertEquals(EnumSet.of(TooMany.C), EnumUtils.processBitVectors(TooMany.class, 4L));
330 assertEquals(EnumSet.of(TooMany.A, TooMany.C), EnumUtils.processBitVectors(TooMany.class, 5L));
331 assertEquals(EnumSet.of(TooMany.B, TooMany.C), EnumUtils.processBitVectors(TooMany.class, 6L));
332 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C), EnumUtils.processBitVectors(TooMany.class, 7L));
333
334 assertEquals(EnumSet.noneOf(TooMany.class), EnumUtils.processBitVectors(TooMany.class, 0L, 0L));
335 assertEquals(EnumSet.of(TooMany.A), EnumUtils.processBitVectors(TooMany.class, 0L, 1L));
336 assertEquals(EnumSet.of(TooMany.B), EnumUtils.processBitVectors(TooMany.class, 0L, 2L));
337 assertEquals(EnumSet.of(TooMany.A, TooMany.B), EnumUtils.processBitVectors(TooMany.class, 0L, 3L));
338 assertEquals(EnumSet.of(TooMany.C), EnumUtils.processBitVectors(TooMany.class, 0L, 4L));
339 assertEquals(EnumSet.of(TooMany.A, TooMany.C), EnumUtils.processBitVectors(TooMany.class, 0L, 5L));
340 assertEquals(EnumSet.of(TooMany.B, TooMany.C), EnumUtils.processBitVectors(TooMany.class, 0L, 6L));
341 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C), EnumUtils.processBitVectors(TooMany.class, 0L, 7L));
342 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C), EnumUtils.processBitVectors(TooMany.class, 0L, 7L));
343
344 assertEquals(EnumSet.of(TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 0L));
345 assertEquals(EnumSet.of(TooMany.A, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 1L));
346 assertEquals(EnumSet.of(TooMany.B, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 2L));
347 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 3L));
348 assertEquals(EnumSet.of(TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 4L));
349 assertEquals(EnumSet.of(TooMany.A, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 5L));
350 assertEquals(EnumSet.of(TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 6L));
351 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 7L));
352 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 7L));
353
354 // demonstrate tolerance of irrelevant high-order digits:
355 assertEquals(EnumSet.of(TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 0L));
356 assertEquals(EnumSet.of(TooMany.A, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 1L));
357 assertEquals(EnumSet.of(TooMany.B, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 2L));
358 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 3L));
359 assertEquals(EnumSet.of(TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 4L));
360 assertEquals(EnumSet.of(TooMany.A, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 5L));
361 assertEquals(EnumSet.of(TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 6L));
362 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 7L));
363 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 7L));
364 }
365
188366 }
189367
190368 enum Traffic {
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3;
17
18 import java.util.BitSet;
19 import java.util.HashSet;
20
21 import org.junit.Assert;
22 import org.junit.Test;
23
24 /**
25 * Test to show whether using BitSet for removeAll() methods is faster than using HashSet.
26 */
27 public class HashSetvBitSetTest {
28
29 private static final int LOOPS = 2000; // number of times to invoke methods
30 private static final int LOOPS2 = 10000;
31
32 @Test
33 public void testTimes() {
34 timeHashSet(10); // warmup
35 timeBitSet(10); // warmup
36 long timeDiff = printTimes(0);
37 timeDiff += printTimes(5);
38 timeDiff += printTimes(10);
39 timeDiff += printTimes(200);
40 timeDiff += printTimes(50);
41 timeDiff += printTimes(100);
42 timeDiff += printTimes(1000);
43 timeDiff += printTimes(2000);
44 Assert.assertTrue(timeDiff <= 0);
45 }
46
47 /**
48 * @return bitSet - HashSet
49 */
50 private long printTimes(final int count) {
51 final long hashSet = timeHashSet(count);
52 final long bitSet = timeBitSet(count);
53 // If percent is less than 100, then bitset is faster
54 System.out.println("Ratio="+(bitSet*100/hashSet)+"% count="+count+" hash="+hashSet+" bits="+bitSet);
55 return bitSet - hashSet;
56 }
57
58 private static long timeHashSet(final int count) {
59 int [] result = new int[0];
60 final long start = System.nanoTime();
61 for (int i = 0; i < LOOPS; i++) {
62 result = testHashSet(count);
63 }
64 final long elapsed = System.nanoTime() - start;
65 Assert.assertEquals(count, result.length);
66 return elapsed;
67 }
68
69 private static long timeBitSet(final int count) {
70 int [] result = new int[0];
71 final long start = System.nanoTime();
72 for (int i = 0; i < LOOPS; i++) {
73 result = testBitSet(count);
74 }
75 final long elapsed = System.nanoTime() - start;
76 Assert.assertEquals(count, result.length);
77 return elapsed;
78 }
79
80 @SuppressWarnings("boxing")
81 private static int[] testHashSet(final int count) {
82 final HashSet<Integer> toRemove = new HashSet<Integer>();
83 int found = 0;
84 for (int i = 0; i < count; i++) {
85 toRemove.add(found++);
86 }
87 return extractIndices(toRemove);
88 }
89
90 private static int[] testBitSet(final int count) {
91 final BitSet toRemove = new BitSet();
92 int found = 0;
93 for (int i = 0; i < count; i++) {
94 toRemove.set(found++);
95 }
96 return extractIndices(toRemove);
97 }
98
99
100 private static int[] extractIndices(final HashSet<Integer> coll) {
101 final int[] result = new int[coll.size()];
102 int i = 0;
103 for (final Integer index : coll) {
104 result[i++] = index.intValue();
105 }
106 return result;
107 }
108
109 private static int[] extractIndices(final BitSet coll) {
110 final int[] result = new int[coll.cardinality()];
111 int i = 0;
112 int j=0;
113 while((j=coll.nextSetBit(j)) != -1) {
114 result[i++] = j++;
115 }
116 return result;
117 }
118
119 @Test
120 public void testTimesExtractOrBitset() {
121 final BitSet toRemove = new BitSet();
122 final int[] array = new int[100];
123 toRemove.set(10, 20);
124 timeBitSetRemoveAll(array, toRemove); // warmup
125 timeExtractRemoveAll(array, toRemove); // warmup
126 long timeDiff = printTimes(100,1);
127 timeDiff += printTimes(100,10);
128 timeDiff += printTimes(100,50);
129 timeDiff += printTimes(100,100);
130 timeDiff += printTimes(1000,10);
131 timeDiff += printTimes(1000,100);
132 timeDiff += printTimes(1000,500);
133 timeDiff += printTimes(1000,1000);
134 Assert.assertTrue(timeDiff <= 0);
135 }
136
137 private long printTimes(final int arraySize, final int bitSetSize) {
138 final int[] array = new int[arraySize];
139 final BitSet remove = new BitSet();
140 for (int i = 0; i < bitSetSize; i++) {
141 remove.set(i);
142 }
143 final long bitSet = timeBitSetRemoveAll(array, remove );
144 final long extract = timeExtractRemoveAll(array, remove);
145 // If percent is less than 100, then direct use of bitset is faster
146 System.out.println("Ratio="+(bitSet*100/extract)+"% array="+array.length+" count="+remove.cardinality()+" extract="+extract+" bitset="+bitSet);
147 return bitSet - extract;
148 }
149
150 private long timeBitSetRemoveAll(final int[] array, final BitSet toRemove) {
151 int[] output = new int[0];
152 final long start = System.nanoTime();
153 for(int i = 0; i < LOOPS2; i++){
154 output = (int[]) ArrayUtils.removeAll(array, toRemove);
155 }
156 final long end = System.nanoTime();
157 Assert.assertEquals(array.length-toRemove.cardinality(), output.length);
158 return end - start;
159 }
160
161 private long timeExtractRemoveAll(final int[] array, final BitSet toRemove) {
162 int[] output = new int[0];
163 final long start = System.nanoTime();
164 for(int i = 0; i < LOOPS2; i++){
165 final int[] extractIndices = extractIndices(toRemove);
166 output = (int[]) ArrayUtils.removeAll((Object)array, extractIndices);
167 }
168 final long end = System.nanoTime();
169 Assert.assertEquals(array.length-toRemove.cardinality(), output.length);
170 return end - start;
171 }
172
173 }
1717 */
1818 package org.apache.commons.lang3;
1919
20 import org.junit.Test;
21 import static org.junit.Assert.*;
2022 import static org.apache.commons.lang3.JavaVersion.JAVA_0_9;
2123 import static org.apache.commons.lang3.JavaVersion.JAVA_1_1;
2224 import static org.apache.commons.lang3.JavaVersion.JAVA_1_2;
2830 import static org.apache.commons.lang3.JavaVersion.JAVA_1_8;
2931 import static org.apache.commons.lang3.JavaVersion.get;
3032 import static org.apache.commons.lang3.JavaVersion.getJavaVersion;
31 import junit.framework.TestCase;
3233
3334 /**
3435 * Unit tests {@link org.apache.commons.lang3.JavaVersion}.
3536 *
3637 * @version $Id: JavaVersionTest.java 918366 2010-03-03 08:56:22Z bayard $
3738 */
38 public class JavaVersionTest extends TestCase {
39 public class JavaVersionTest {
3940
41 @Test
4042 public void testGetJavaVersion() {
4143 assertEquals("0.9 failed", JAVA_0_9, get("0.9"));
4244 assertEquals("1.1 failed", JAVA_1_1, get("1.1"));
5153 assertEquals("Wrapper method failed", get("1.5"), getJavaVersion("1.5"));
5254 }
5355
56 @Test
5457 public void testAtLeast() {
5558 assertFalse("1.2 at least 1.5 passed", JAVA_1_2.atLeast(JAVA_1_5));
5659 assertTrue("1.5 at least 1.2 failed", JAVA_1_5.atLeast(JAVA_1_2));
6063 assertFalse("0.9 at least 1.6 passed", JAVA_0_9.atLeast(JAVA_1_6));
6164 }
6265
66 @Test
6367 public void testToString() {
6468 assertEquals("1.2", JAVA_1_2.toString());
6569 }
1616 package org.apache.commons.lang3;
1717
1818 import static org.apache.commons.lang3.JavaVersion.JAVA_1_4;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertNotNull;
22 import static org.junit.Assert.assertNull;
23 import static org.junit.Assert.assertSame;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
1926
2027 import java.lang.reflect.Constructor;
2128 import java.lang.reflect.Modifier;
2734 import java.util.Locale;
2835 import java.util.Set;
2936
30 import junit.framework.TestCase;
37 import org.junit.Before;
38 import org.junit.Test;
3139
3240 /**
3341 * Unit tests for {@link LocaleUtils}.
3442 *
35 * @version $Id: LocaleUtilsTest.java 1144929 2011-07-10 18:26:16Z ggregory $
43 * @version $Id: LocaleUtilsTest.java 1555044 2014-01-03 10:27:30Z britter $
3644 */
37 public class LocaleUtilsTest extends TestCase {
45 public class LocaleUtilsTest {
3846
3947 private static final Locale LOCALE_EN = new Locale("en", "");
4048 private static final Locale LOCALE_EN_US = new Locale("en", "US");
4452 private static final Locale LOCALE_QQ = new Locale("qq", "");
4553 private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ");
4654
47 /**
48 * Constructor.
49 *
50 * @param name
51 */
52 public LocaleUtilsTest(String name) {
53 super(name);
54 }
55
56 @Override
55
56
57 @Before
5758 public void setUp() throws Exception {
58 super.setUp();
59
6059 // Testing #LANG-304. Must be called before availableLocaleSet is called.
6160 LocaleUtils.isAvailableLocale(Locale.getDefault());
6261 }
6564 /**
6665 * Test that constructors are public, and work, etc.
6766 */
67 @Test
6868 public void testConstructor() {
6969 assertNotNull(new LocaleUtils());
70 Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors();
70 final Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors();
7171 assertEquals(1, cons.length);
72 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
73 assertEquals(true, Modifier.isPublic(LocaleUtils.class.getModifiers()));
74 assertEquals(false, Modifier.isFinal(LocaleUtils.class.getModifiers()));
72 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
73 assertTrue(Modifier.isPublic(LocaleUtils.class.getModifiers()));
74 assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers()));
7575 }
7676
7777 //-----------------------------------------------------------------------
8080 *
8181 * @param language the language string
8282 */
83 private void assertValidToLocale(String language) {
84 Locale locale = LocaleUtils.toLocale(language);
83 private static void assertValidToLocale(final String language) {
84 final Locale locale = LocaleUtils.toLocale(language);
8585 assertNotNull("valid locale", locale);
8686 assertEquals(language, locale.getLanguage());
8787 //country and variant are empty
88 assertTrue(locale.getCountry() == null || locale.getCountry().length() == 0);
89 assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0);
88 assertTrue(locale.getCountry() == null || locale.getCountry().isEmpty());
89 assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty());
9090 }
9191
9292 /**
9696 * @param language of the resulting Locale
9797 * @param country of the resulting Locale
9898 */
99 private void assertValidToLocale(String localeString, String language, String country) {
100 Locale locale = LocaleUtils.toLocale(localeString);
99 private static void assertValidToLocale(final String localeString, final String language, final String country) {
100 final Locale locale = LocaleUtils.toLocale(localeString);
101101 assertNotNull("valid locale", locale);
102102 assertEquals(language, locale.getLanguage());
103103 assertEquals(country, locale.getCountry());
104104 //variant is empty
105 assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0);
105 assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty());
106106 }
107107
108108 /**
113113 * @param country of the resulting Locale
114114 * @param variant of the resulting Locale
115115 */
116 private void assertValidToLocale(
117 String localeString, String language,
118 String country, String variant) {
119 Locale locale = LocaleUtils.toLocale(localeString);
116 private static void assertValidToLocale(
117 final String localeString, final String language,
118 final String country, final String variant) {
119 final Locale locale = LocaleUtils.toLocale(localeString);
120120 assertNotNull("valid locale", locale);
121121 assertEquals(language, locale.getLanguage());
122122 assertEquals(country, locale.getCountry());
123123 assertEquals(variant, locale.getVariant());
124
125124 }
126125
127126 /**
128127 * Test toLocale() method.
129128 */
129 @Test
130130 public void testToLocale_1Part() {
131 assertEquals(null, LocaleUtils.toLocale((String) null));
131 assertNull(LocaleUtils.toLocale((String) null));
132132
133133 assertValidToLocale("us");
134134 assertValidToLocale("fr");
136136 assertValidToLocale("zh");
137137 // Valid format but lang doesnt exist, should make instance anyway
138138 assertValidToLocale("qq");
139
139 // LANG-941: JDK 8 introduced the empty locale as one of the default locales
140 assertValidToLocale("");
141
140142 try {
141143 LocaleUtils.toLocale("Us");
142144 fail("Should fail if not lowercase");
143 } catch (IllegalArgumentException iae) {}
145 } catch (final IllegalArgumentException iae) {}
144146 try {
145147 LocaleUtils.toLocale("US");
146148 fail("Should fail if not lowercase");
147 } catch (IllegalArgumentException iae) {}
149 } catch (final IllegalArgumentException iae) {}
148150 try {
149151 LocaleUtils.toLocale("uS");
150152 fail("Should fail if not lowercase");
151 } catch (IllegalArgumentException iae) {}
153 } catch (final IllegalArgumentException iae) {}
152154 try {
153155 LocaleUtils.toLocale("u#");
154156 fail("Should fail if not lowercase");
155 } catch (IllegalArgumentException iae) {}
157 } catch (final IllegalArgumentException iae) {}
156158
157159 try {
158160 LocaleUtils.toLocale("u");
159161 fail("Must be 2 chars if less than 5");
160 } catch (IllegalArgumentException iae) {}
162 } catch (final IllegalArgumentException iae) {}
161163
162164 try {
163165 LocaleUtils.toLocale("uuu");
164166 fail("Must be 2 chars if less than 5");
165 } catch (IllegalArgumentException iae) {}
167 } catch (final IllegalArgumentException iae) {}
166168
167169 try {
168170 LocaleUtils.toLocale("uu_U");
169171 fail("Must be 2 chars if less than 5");
170 } catch (IllegalArgumentException iae) {}
172 } catch (final IllegalArgumentException iae) {}
171173 }
172174
173175 /**
174176 * Test toLocale() method.
175177 */
178 @Test
176179 public void testToLocale_2Part() {
177180 assertValidToLocale("us_EN", "us", "EN");
178181 //valid though doesnt exist
181184 try {
182185 LocaleUtils.toLocale("us-EN");
183186 fail("Should fail as not underscore");
184 } catch (IllegalArgumentException iae) {}
187 } catch (final IllegalArgumentException iae) {}
185188 try {
186189 LocaleUtils.toLocale("us_En");
187190 fail("Should fail second part not uppercase");
188 } catch (IllegalArgumentException iae) {}
191 } catch (final IllegalArgumentException iae) {}
189192 try {
190193 LocaleUtils.toLocale("us_en");
191194 fail("Should fail second part not uppercase");
192 } catch (IllegalArgumentException iae) {}
195 } catch (final IllegalArgumentException iae) {}
193196 try {
194197 LocaleUtils.toLocale("us_eN");
195198 fail("Should fail second part not uppercase");
196 } catch (IllegalArgumentException iae) {}
199 } catch (final IllegalArgumentException iae) {}
197200 try {
198201 LocaleUtils.toLocale("uS_EN");
199202 fail("Should fail first part not lowercase");
200 } catch (IllegalArgumentException iae) {}
203 } catch (final IllegalArgumentException iae) {}
201204 try {
202205 LocaleUtils.toLocale("us_E3");
203206 fail("Should fail second part not uppercase");
204 } catch (IllegalArgumentException iae) {}
207 } catch (final IllegalArgumentException iae) {}
205208 }
206209
207210 /**
208211 * Test toLocale() method.
209212 */
213 @Test
210214 public void testToLocale_3Part() {
211215 assertValidToLocale("us_EN_A", "us", "EN", "A");
212216 // this isn't pretty, but was caused by a jdk bug it seems
222226 try {
223227 LocaleUtils.toLocale("us_EN-a");
224228 fail("Should fail as not underscore");
225 } catch (IllegalArgumentException iae) {}
229 } catch (final IllegalArgumentException iae) {}
226230 try {
227231 LocaleUtils.toLocale("uu_UU_");
228232 fail("Must be 3, 5 or 7+ in length");
229 } catch (IllegalArgumentException iae) {}
233 } catch (final IllegalArgumentException iae) {}
230234 }
231235
232236 //-----------------------------------------------------------------------
237241 * @param defaultLocale the input default locale
238242 * @param expected expected results
239243 */
240 private void assertLocaleLookupList(Locale locale, Locale defaultLocale, Locale[] expected) {
241 List<Locale> localeList = defaultLocale == null ?
244 private static void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected) {
245 final List<Locale> localeList = defaultLocale == null ?
242246 LocaleUtils.localeLookupList(locale) :
243247 LocaleUtils.localeLookupList(locale, defaultLocale);
244248
251255 /**
252256 * Test localeLookupList() method.
253257 */
258 @Test
254259 public void testLocaleLookupList_Locale() {
255260 assertLocaleLookupList(null, null, new Locale[0]);
256261 assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ});
270275 /**
271276 * Test localeLookupList() method.
272277 */
278 @Test
273279 public void testLocaleLookupList_LocaleLocale() {
274280 assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ,
275281 new Locale[]{LOCALE_QQ});
324330 /**
325331 * Test availableLocaleList() method.
326332 */
333 @Test
327334 public void testAvailableLocaleList() {
328 List<Locale> list = LocaleUtils.availableLocaleList();
329 List<Locale> list2 = LocaleUtils.availableLocaleList();
335 final List<Locale> list = LocaleUtils.availableLocaleList();
336 final List<Locale> list2 = LocaleUtils.availableLocaleList();
330337 assertNotNull(list);
331338 assertSame(list, list2);
332339 assertUnmodifiableCollection(list);
333340
334 Locale[] jdkLocaleArray = Locale.getAvailableLocales();
335 List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
341 final Locale[] jdkLocaleArray = Locale.getAvailableLocales();
342 final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
336343 assertEquals(jdkLocaleList, list);
337344 }
338345
340347 /**
341348 * Test availableLocaleSet() method.
342349 */
350 @Test
343351 public void testAvailableLocaleSet() {
344 Set<Locale> set = LocaleUtils.availableLocaleSet();
345 Set<Locale> set2 = LocaleUtils.availableLocaleSet();
352 final Set<Locale> set = LocaleUtils.availableLocaleSet();
353 final Set<Locale> set2 = LocaleUtils.availableLocaleSet();
346354 assertNotNull(set);
347355 assertSame(set, set2);
348356 assertUnmodifiableCollection(set);
349357
350 Locale[] jdkLocaleArray = Locale.getAvailableLocales();
351 List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
352 Set<Locale> jdkLocaleSet = new HashSet<Locale>(jdkLocaleList);
358 final Locale[] jdkLocaleArray = Locale.getAvailableLocales();
359 final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
360 final Set<Locale> jdkLocaleSet = new HashSet<Locale>(jdkLocaleList);
353361 assertEquals(jdkLocaleSet, set);
354362 }
355363
357365 /**
358366 * Test availableLocaleSet() method.
359367 */
368 @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long
369 @Test
360370 public void testIsAvailableLocale() {
361 Set<Locale> set = LocaleUtils.availableLocaleSet();
371 final Set<Locale> set = LocaleUtils.availableLocaleSet();
362372 assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN));
363373 assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US));
364374 assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ));
378388 * @param country
379389 * @param languages array of languages that should be returned
380390 */
381 private void assertLanguageByCountry(String country, String[] languages) {
382 List<Locale> list = LocaleUtils.languagesByCountry(country);
383 List<Locale> list2 = LocaleUtils.languagesByCountry(country);
391 private static void assertLanguageByCountry(final String country, final String[] languages) {
392 final List<Locale> list = LocaleUtils.languagesByCountry(country);
393 final List<Locale> list2 = LocaleUtils.languagesByCountry(country);
384394 assertNotNull(list);
385395 assertSame(list, list2);
386396 //search through langauges
387 for (String language : languages) {
388 Iterator<Locale> iterator = list.iterator();
397 for (final String language : languages) {
398 final Iterator<Locale> iterator = list.iterator();
389399 boolean found = false;
390400 // see if it was returned by the set
391401 while (iterator.hasNext()) {
392 Locale locale = iterator.next();
402 final Locale locale = iterator.next();
393403 // should have an en empty variant
394404 assertTrue(locale.getVariant() == null
395 || locale.getVariant().length() == 0);
405 || locale.getVariant().isEmpty());
396406 assertEquals(country, locale.getCountry());
397407 if (language.equals(locale.getLanguage())) {
398408 found = true;
410420 /**
411421 * Test languagesByCountry() method.
412422 */
423 @Test
413424 public void testLanguagesByCountry() {
414425 assertLanguageByCountry(null, new String[0]);
415426 assertLanguageByCountry("GB", new String[]{"en"});
428439 * @param language
429440 * @param countries array of countries that should be returned
430441 */
431 private void assertCountriesByLanguage(String language, String[] countries) {
432 List<Locale> list = LocaleUtils.countriesByLanguage(language);
433 List<Locale> list2 = LocaleUtils.countriesByLanguage(language);
442 private static void assertCountriesByLanguage(final String language, final String[] countries) {
443 final List<Locale> list = LocaleUtils.countriesByLanguage(language);
444 final List<Locale> list2 = LocaleUtils.countriesByLanguage(language);
434445 assertNotNull(list);
435446 assertSame(list, list2);
436447 //search through langauges
437 for (String countrie : countries) {
438 Iterator<Locale> iterator = list.iterator();
448 for (final String countrie : countries) {
449 final Iterator<Locale> iterator = list.iterator();
439450 boolean found = false;
440451 // see if it was returned by the set
441452 while (iterator.hasNext()) {
442 Locale locale = iterator.next();
453 final Locale locale = iterator.next();
443454 // should have an en empty variant
444455 assertTrue(locale.getVariant() == null
445 || locale.getVariant().length() == 0);
456 || locale.getVariant().isEmpty());
446457 assertEquals(language, locale.getLanguage());
447458 if (countrie.equals(locale.getCountry())) {
448459 found = true;
460471 /**
461472 * Test countriesByLanguage() method.
462473 */
474 @Test
463475 public void testCountriesByLanguage() {
464476 assertCountriesByLanguage(null, new String[0]);
465477 assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"});
470482 /**
471483 * @param coll the collection to check
472484 */
473 private static void assertUnmodifiableCollection(Collection<?> coll) {
485 private static void assertUnmodifiableCollection(final Collection<?> coll) {
474486 try {
475487 coll.add(null);
476488 fail();
477 } catch (UnsupportedOperationException ex) {}
489 } catch (final UnsupportedOperationException ex) {}
478490 }
479491
480492 /**
481493 * Tests #LANG-328 - only language+variant
482494 */
495 @Test
483496 public void testLang328() {
497 assertValidToLocale("fr__P", "fr", "", "P");
484498 assertValidToLocale("fr__POSIX", "fr", "", "POSIX");
485499 }
486500
487 }
501 /**
502 * Tests #LANG-865, strings starting with an underscore.
503 */
504 @Test
505 public void testLang865() {
506 assertValidToLocale("_GB", "", "GB", "");
507 assertValidToLocale("_GB_P", "", "GB", "P");
508 assertValidToLocale("_GB_POSIX", "", "GB", "POSIX");
509 try {
510 LocaleUtils.toLocale("_G");
511 fail("Must be at least 3 chars if starts with underscore");
512 } catch (final IllegalArgumentException iae) {
513 }
514 try {
515 LocaleUtils.toLocale("_Gb");
516 fail("Must be uppercase if starts with underscore");
517 } catch (final IllegalArgumentException iae) {
518 }
519 try {
520 LocaleUtils.toLocale("_gB");
521 fail("Must be uppercase if starts with underscore");
522 } catch (final IllegalArgumentException iae) {
523 }
524 try {
525 LocaleUtils.toLocale("_1B");
526 fail("Must be letter if starts with underscore");
527 } catch (final IllegalArgumentException iae) {
528 }
529 try {
530 LocaleUtils.toLocale("_G1");
531 fail("Must be letter if starts with underscore");
532 } catch (final IllegalArgumentException iae) {
533 }
534 try {
535 LocaleUtils.toLocale("_GB_");
536 fail("Must be at least 5 chars if starts with underscore");
537 } catch (final IllegalArgumentException iae) {
538 }
539 try {
540 LocaleUtils.toLocale("_GBAP");
541 fail("Must have underscore after the country if starts with underscore and is at least 5 chars");
542 } catch (final IllegalArgumentException iae) {
543 }
544 }
545
546 @Test
547 public void testParseAllLocales() {
548 Locale[] locales = Locale.getAvailableLocales();
549 int failures = 0;
550 for (Locale l : locales) {
551 // Check if it's possible to recreate the Locale using just the standard constructor
552 Locale locale = new Locale(l.getLanguage(), l.getCountry(), l.getVariant());
553 if (l.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales
554 String str = l.toString();
555 // Look for the script/extension suffix
556 int suff = str.indexOf("_#");
557 if (suff == - 1) {
558 suff = str.indexOf("#");
559 }
560 if (suff >= 0) { // we have a suffix
561 try {
562 LocaleUtils.toLocale(str); // shouuld cause IAE
563 System.out.println("Should not have parsed: " + str);
564 failures++;
565 continue; // try next Locale
566 } catch (IllegalArgumentException iae) {
567 // expected; try without suffix
568 str = str.substring(0, suff);
569 }
570 }
571 Locale loc = LocaleUtils.toLocale(str);
572 if (!l.equals(loc)) {
573 System.out.println("Failed to parse: " + str);
574 failures++;
575 }
576 }
577 }
578 if (failures > 0) {
579 fail("Failed "+failures+" test(s)");
580 }
581 }
582
583 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3;
17
18 import org.junit.Test;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertNotNull;
21
22 /**
23 * Unit tests {@link org.apache.commons.lang3.NotImplementedException}.
24 *
25 * @version $Id: NotImplementedExceptionTest.java 905628 2010-02-02 13:29:55Z niallp $
26 */
27 public class NotImplementedExceptionTest {
28
29 @Test
30 public void testConstructors() {
31 Throwable nested = new RuntimeException();
32 String message = "Not Implemented";
33 String code = "CODE";
34
35 NotImplementedException nie = new NotImplementedException(message);
36 assertCorrect("Issue in (String)", nie, message, null, null);
37 nie = new NotImplementedException(nested);
38 assertCorrect("Issue in (Throwable)", nie, nested.toString(), nested, null);
39 nie = new NotImplementedException(message, nested);
40 assertCorrect("Issue in (String, Throwable)", nie, message, nested, null);
41 nie = new NotImplementedException(message, code);
42 assertCorrect("Issue in (String, String)", nie, message, null, code);
43 nie = new NotImplementedException(nested, code);
44 assertCorrect("Issue in (Throwable, String)", nie, nested.toString(), nested, code);
45 nie = new NotImplementedException(message, nested, code);
46 assertCorrect("Issue in (String, Throwable, String)", nie, message, nested, code);
47 }
48
49 private void assertCorrect(String assertMessage, NotImplementedException nie, String message, Throwable nested, String code) {
50 assertNotNull(assertMessage + ": target is null", nie);
51 assertEquals(assertMessage + ": Message not equal", message, nie.getMessage());
52 assertEquals(assertMessage + ": Nested throwable not equal", nested, nie.getCause());
53 assertEquals(assertMessage + ": Code not equal", code, nie.getCode());
54 }
55 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.*;
19
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertNotSame;
22 import static org.junit.Assert.assertNull;
23 import static org.junit.Assert.assertSame;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
26
27 import java.io.IOException;
2028 import java.lang.reflect.Constructor;
2129 import java.lang.reflect.Modifier;
2230 import java.util.ArrayList;
2836
2937 import org.apache.commons.lang3.exception.CloneFailedException;
3038 import org.apache.commons.lang3.mutable.MutableObject;
39 import org.apache.commons.lang3.text.StrBuilder;
3140 import org.junit.Test;
3241
3342 /**
3443 * Unit tests {@link org.apache.commons.lang3.ObjectUtils}.
3544 *
36 * @version $Id: ObjectUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
45 * @version $Id: ObjectUtilsTest.java 1533515 2013-10-18 15:36:22Z sebb $
3746 */
47 @SuppressWarnings("deprecation") // deliberate use of deprecated code
3848 public class ObjectUtilsTest {
3949 private static final String FOO = "foo";
4050 private static final String BAR = "bar";
4353 @Test
4454 public void testConstructor() {
4555 assertNotNull(new ObjectUtils());
46 Constructor<?>[] cons = ObjectUtils.class.getDeclaredConstructors();
56 final Constructor<?>[] cons = ObjectUtils.class.getDeclaredConstructors();
4757 assertEquals(1, cons.length);
4858 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
4959 assertTrue(Modifier.isPublic(ObjectUtils.class.getModifiers()));
5363 //-----------------------------------------------------------------------
5464 @Test
5565 public void testIsNull() {
56 Object o = FOO;
57 Object dflt = BAR;
66 final Object o = FOO;
67 final Object dflt = BAR;
5868 assertSame("dflt was not returned when o was null", dflt, ObjectUtils.defaultIfNull(null, dflt));
5969 assertSame("dflt was returned when o was not null", o, ObjectUtils.defaultIfNull(o, dflt));
6070 }
6373 public void testFirstNonNull() {
6474 assertEquals(null, ObjectUtils.firstNonNull(null, null));
6575 assertEquals("", ObjectUtils.firstNonNull(null, ""));
66 String firstNonNullGenerics = ObjectUtils.firstNonNull(null, null, "123", "456");
76 final String firstNonNullGenerics = ObjectUtils.firstNonNull(null, null, "123", "456");
6777 assertEquals("123", firstNonNullGenerics);
6878 assertEquals("123", ObjectUtils.firstNonNull("123", null, "456", null));
6979 assertEquals(null, ObjectUtils.firstNonNull());
104114
105115 @Test
106116 public void testHashCodeMulti_multiple_emptyArray() {
107 Object[] array = new Object[0];
117 final Object[] array = new Object[0];
108118 assertEquals(1, ObjectUtils.hashCodeMulti(array));
109119 }
110120
111121 @Test
112122 public void testHashCodeMulti_multiple_nullArray() {
113 Object[] array = null;
123 final Object[] array = null;
114124 assertEquals(1, ObjectUtils.hashCodeMulti(array));
115125 }
116126
117127 @Test
118128 public void testHashCodeMulti_multiple_likeList() {
119 List<Object> list0 = new ArrayList<Object>(Arrays.asList());
129 final List<Object> list0 = new ArrayList<Object>(Arrays.asList());
120130 assertEquals(list0.hashCode(), ObjectUtils.hashCodeMulti());
121131
122 List<Object> list1 = new ArrayList<Object>(Arrays.asList("a"));
132 final List<Object> list1 = new ArrayList<Object>(Arrays.asList("a"));
123133 assertEquals(list1.hashCode(), ObjectUtils.hashCodeMulti("a"));
124134
125 List<Object> list2 = new ArrayList<Object>(Arrays.asList("a", "b"));
135 final List<Object> list2 = new ArrayList<Object>(Arrays.asList("a", "b"));
126136 assertEquals(list2.hashCode(), ObjectUtils.hashCodeMulti("a", "b"));
127137
128 List<Object> list3 = new ArrayList<Object>(Arrays.asList("a", "b", "c"));
138 final List<Object> list3 = new ArrayList<Object>(Arrays.asList("a", "b", "c"));
129139 assertEquals(list3.hashCode(), ObjectUtils.hashCodeMulti("a", "b", "c"));
130140 }
131141
171181 // }
172182
173183 @Test
174 public void testIdentityToString() {
184 public void testIdentityToStringStringBuffer() {
185 final Integer i = Integer.valueOf(45);
186 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
187
188 final StringBuffer buffer = new StringBuffer();
189 ObjectUtils.identityToString(buffer, i);
190 assertEquals(expected, buffer.toString());
191
192 try {
193 ObjectUtils.identityToString((StringBuffer)null, "tmp");
194 fail("NullPointerException expected");
195 } catch(final NullPointerException npe) {
196 }
197 try {
198 ObjectUtils.identityToString(new StringBuffer(), null);
199 fail("NullPointerException expected");
200 } catch(final NullPointerException npe) {
201 }
202 }
203
204 @Test
205 public void testIdentityToStringStringBuilder() {
175206 assertEquals(null, ObjectUtils.identityToString(null));
176207 assertEquals(
177208 "java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)),
178209 ObjectUtils.identityToString(FOO));
179 Integer i = Integer.valueOf(90);
180 String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
210 final Integer i = Integer.valueOf(90);
211 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
212
181213 assertEquals(expected, ObjectUtils.identityToString(i));
182 StringBuffer buffer = new StringBuffer();
183 ObjectUtils.identityToString(buffer, i);
184 assertEquals(expected, buffer.toString());
185
186 try {
187 ObjectUtils.identityToString(null, "tmp");
188 fail("NullPointerException expected");
189 } catch(NullPointerException npe) {
190 }
191 try {
192 ObjectUtils.identityToString(new StringBuffer(), null);
193 fail("NullPointerException expected");
194 } catch(NullPointerException npe) {
214
215 final StringBuilder builder = new StringBuilder();
216 ObjectUtils.identityToString(builder, i);
217 assertEquals(expected, builder.toString());
218
219 try {
220 ObjectUtils.identityToString((StringBuilder)null, "tmp");
221 fail("NullPointerException expected");
222 } catch(final NullPointerException npe) {
223 }
224
225 try {
226 ObjectUtils.identityToString(new StringBuilder(), null);
227 fail("NullPointerException expected");
228 } catch(final NullPointerException npe) {
229 }
230 }
231
232 @Test
233 public void testIdentityToStringStrBuilder() {
234 final Integer i = Integer.valueOf(102);
235 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
236
237 final StrBuilder builder = new StrBuilder();
238 ObjectUtils.identityToString(builder, i);
239 assertEquals(expected, builder.toString());
240
241 try {
242 ObjectUtils.identityToString((StrBuilder)null, "tmp");
243 fail("NullPointerException expected");
244 } catch(final NullPointerException npe) {
245 }
246
247 try {
248 ObjectUtils.identityToString(new StrBuilder(), null);
249 fail("NullPointerException expected");
250 } catch(final NullPointerException npe) {
251 }
252 }
253
254 @Test
255 public void testIdentityToStringAppendable() {
256 final Integer i = Integer.valueOf(121);
257 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
258
259 try {
260 final Appendable appendable = new StringBuilder();
261 ObjectUtils.identityToString(appendable, i);
262 assertEquals(expected, appendable.toString());
263 } catch(IOException ex) {
264 fail("IOException unexpected");
265 }
266
267 try {
268 ObjectUtils.identityToString((Appendable)null, "tmp");
269 fail("NullPointerException expected");
270 } catch(final NullPointerException npe) {
271 } catch (IOException ex) {
272 }
273
274 try {
275 ObjectUtils.identityToString((Appendable)(new StringBuilder()), null);
276 fail("NullPointerException expected");
277 } catch(final NullPointerException npe) {
278 } catch (IOException ex) {
195279 }
196280 }
197281
207291 assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, BAR) );
208292 }
209293
294 @SuppressWarnings("cast") // 1 OK, because we are checking for code change
210295 @Test
211296 public void testNull() {
212297 assertNotNull(ObjectUtils.NULL);
298 // 1 Check that NULL really is a Null i.e. the definition has not been changed
213299 assertTrue(ObjectUtils.NULL instanceof ObjectUtils.Null);
214300 assertSame(ObjectUtils.NULL, SerializationUtils.clone(ObjectUtils.NULL));
215301 }
216302
217303 @Test
218304 public void testMax() {
219 Calendar calendar = Calendar.getInstance();
220 Date nonNullComparable1 = calendar.getTime();
221 Date nonNullComparable2 = calendar.getTime();
222 String[] nullAray = null;
305 final Calendar calendar = Calendar.getInstance();
306 final Date nonNullComparable1 = calendar.getTime();
307 final Date nonNullComparable2 = calendar.getTime();
308 final String[] nullAray = null;
223309
224310 calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 );
225 Date minComparable = calendar.getTime();
311 final Date minComparable = calendar.getTime();
226312
227313 assertNotSame( nonNullComparable1, nonNullComparable2 );
228314
242328
243329 @Test
244330 public void testMin() {
245 Calendar calendar = Calendar.getInstance();
246 Date nonNullComparable1 = calendar.getTime();
247 Date nonNullComparable2 = calendar.getTime();
248 String[] nullAray = null;
331 final Calendar calendar = Calendar.getInstance();
332 final Date nonNullComparable1 = calendar.getTime();
333 final Date nonNullComparable2 = calendar.getTime();
334 final String[] nullAray = null;
249335
250336 calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 );
251 Date minComparable = calendar.getTime();
337 final Date minComparable = calendar.getTime();
252338
253339 assertNotSame( nonNullComparable1, nonNullComparable2 );
254340
271357 */
272358 @Test
273359 public void testCompare() {
274 Integer one = Integer.valueOf(1);
275 Integer two = Integer.valueOf(2);
276 Integer nullValue = null;
360 final Integer one = Integer.valueOf(1);
361 final Integer two = Integer.valueOf(2);
362 final Integer nullValue = null;
277363
278364 assertEquals("Null Null false", 0, ObjectUtils.compare(nullValue, nullValue));
279365 assertEquals("Null Null true", 0, ObjectUtils.compare(nullValue, nullValue, true));
317403
318404 @Test
319405 public void testComparatorMedian() {
320 CharSequenceComparator cmp = new CharSequenceComparator();
321 NonComparableCharSequence foo = new NonComparableCharSequence("foo");
322 NonComparableCharSequence bar = new NonComparableCharSequence("bar");
323 NonComparableCharSequence baz = new NonComparableCharSequence("baz");
324 NonComparableCharSequence blah = new NonComparableCharSequence("blah");
325 NonComparableCharSequence wah = new NonComparableCharSequence("wah");
406 final CharSequenceComparator cmp = new CharSequenceComparator();
407 final NonComparableCharSequence foo = new NonComparableCharSequence("foo");
408 final NonComparableCharSequence bar = new NonComparableCharSequence("bar");
409 final NonComparableCharSequence baz = new NonComparableCharSequence("baz");
410 final NonComparableCharSequence blah = new NonComparableCharSequence("blah");
411 final NonComparableCharSequence wah = new NonComparableCharSequence("wah");
326412 assertSame(foo, ObjectUtils.median(cmp, foo));
327413 assertSame(bar, ObjectUtils.median(cmp, foo, bar));
328414 assertSame(baz, ObjectUtils.median(cmp, foo, bar, baz));
440526 }
441527 }
442528
529 @Test
530 public void testConstMethods() {
531
532 // To truly test the CONST() method, we'd want to look in the
533 // bytecode to see if the literals were folded into the
534 // class, or if the bytecode kept the method call.
535
536 assertTrue("CONST(boolean)", ObjectUtils.CONST(true));
537 assertEquals("CONST(byte)", (byte) 3, ObjectUtils.CONST((byte) 3));
538 assertEquals("CONST(char)", (char) 3, ObjectUtils.CONST((char) 3));
539 assertEquals("CONST(short)", (short) 3, ObjectUtils.CONST((short) 3));
540 assertEquals("CONST(int)", 3, ObjectUtils.CONST(3));
541 assertEquals("CONST(long)", 3l, ObjectUtils.CONST(3l));
542 assertEquals("CONST(float)", 3f, ObjectUtils.CONST(3f), 0);
543 assertEquals("CONST(double)", 3.0, ObjectUtils.CONST(3.0), 0);
544 assertEquals("CONST(Object)", "abc", ObjectUtils.CONST("abc"));
545
546 // Make sure documentation examples from Javadoc all work
547 // (this fixed a lot of my bugs when I these!)
548 //
549 // My bugs should be in a software engineering textbook
550 // for "Can you screw this up?" The answer is, yes,
551 // you can even screw this up. (When you == Julius)
552 // .
553 final boolean MAGIC_FLAG = ObjectUtils.CONST(true);
554 final byte MAGIC_BYTE1 = ObjectUtils.CONST((byte) 127);
555 final byte MAGIC_BYTE2 = ObjectUtils.CONST_BYTE(127);
556 final char MAGIC_CHAR = ObjectUtils.CONST('a');
557 final short MAGIC_SHORT1 = ObjectUtils.CONST((short) 123);
558 final short MAGIC_SHORT2 = ObjectUtils.CONST_SHORT(127);
559 final int MAGIC_INT = ObjectUtils.CONST(123);
560 final long MAGIC_LONG1 = ObjectUtils.CONST(123L);
561 final long MAGIC_LONG2 = ObjectUtils.CONST(3);
562 final float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
563 final double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
564 final String MAGIC_STRING = ObjectUtils.CONST("abc");
565
566 assertTrue(MAGIC_FLAG);
567 assertEquals(127, MAGIC_BYTE1);
568 assertEquals(127, MAGIC_BYTE2);
569 assertEquals('a', MAGIC_CHAR);
570 assertEquals(123, MAGIC_SHORT1);
571 assertEquals(127, MAGIC_SHORT2);
572 assertEquals(123, MAGIC_INT);
573 assertEquals(123, MAGIC_LONG1);
574 assertEquals(3, MAGIC_LONG2);
575 assertEquals(1.0f, MAGIC_FLOAT, 0.0f);
576 assertEquals(1.0, MAGIC_DOUBLE, 0.0);
577 assertEquals("abc", MAGIC_STRING);
578
579 try {
580 ObjectUtils.CONST_BYTE(-129);
581 fail("CONST_BYTE(-129): IllegalArgumentException should have been thrown.");
582 } catch (final IllegalArgumentException iae) {
583
584 }
585 try {
586 ObjectUtils.CONST_BYTE(128);
587 fail("CONST_BYTE(128): IllegalArgumentException should have been thrown.");
588 } catch (final IllegalArgumentException iae) {
589
590 }
591 try {
592 ObjectUtils.CONST_SHORT(-32769);
593 fail("CONST_SHORT(-32769): IllegalArgumentException should have been thrown.");
594 } catch (final IllegalArgumentException iae) {
595
596 }
597 try {
598 ObjectUtils.CONST_BYTE(32768);
599 fail("CONST_SHORT(32768): IllegalArgumentException should have been thrown.");
600 } catch (final IllegalArgumentException iae) {
601
602 }
603
604 }
605
443606 /**
444607 * String that is cloneable.
445608 */
473636 *
474637 * @param value
475638 */
476 public NonComparableCharSequence(String value) {
639 public NonComparableCharSequence(final String value) {
477640 super();
478641 Validate.notNull(value);
479642 this.value = value;
480643 }
481644
482 public char charAt(int arg0) {
645 @Override
646 public char charAt(final int arg0) {
483647 return value.charAt(arg0);
484648 }
485649
650 @Override
486651 public int length() {
487652 return value.length();
488653 }
489654
490 public CharSequence subSequence(int arg0, int arg1) {
655 @Override
656 public CharSequence subSequence(final int arg0, final int arg1) {
491657 return value.subSequence(arg0, arg1);
492658 }
493659
499665
500666 static final class CharSequenceComparator implements Comparator<CharSequence> {
501667
502 public int compare(CharSequence o1, CharSequence o2) {
668 @Override
669 public int compare(final CharSequence o1, final CharSequence o2) {
503670 return o1.toString().compareTo(o2.toString());
504671 }
505672
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertTrue;
22 import static org.junit.Assert.fail;
23
1824 import java.lang.reflect.Constructor;
1925 import java.lang.reflect.Modifier;
2026 import java.util.Random;
2127
28 import org.junit.Test;
29
2230 /**
2331 * Unit tests {@link org.apache.commons.lang3.RandomStringUtils}.
2432 *
25 * @version $Id: RandomStringUtilsTest.java 1199894 2011-11-09 17:53:59Z ggregory $
33 * @version $Id: RandomStringUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2634 */
27 public class RandomStringUtilsTest extends junit.framework.TestCase {
28 /**
29 * Construct a new instance of RandomStringUtilsTest with the specified name
30 */
31 public RandomStringUtilsTest(String name) {
32 super(name);
33 }
35 public class RandomStringUtilsTest {
3436
3537 //-----------------------------------------------------------------------
38 @Test
3639 public void testConstructor() {
3740 assertNotNull(new RandomStringUtils());
38 Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors();
41 final Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors();
3942 assertEquals(1, cons.length);
40 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
41 assertEquals(true, Modifier.isPublic(RandomStringUtils.class.getModifiers()));
42 assertEquals(false, Modifier.isFinal(RandomStringUtils.class.getModifiers()));
43 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
44 assertTrue(Modifier.isPublic(RandomStringUtils.class.getModifiers()));
45 assertFalse(Modifier.isFinal(RandomStringUtils.class.getModifiers()));
4346 }
4447
4548 //-----------------------------------------------------------------------
4649 /**
4750 * Test the implementation
4851 */
52 @Test
4953 public void testRandomStringUtils() {
5054 String r1 = RandomStringUtils.random(50);
5155 assertEquals("random(50) length", 50, r1.length());
6468 r1 = RandomStringUtils.randomAlphabetic(50);
6569 assertEquals("randomAlphabetic(50)", 50, r1.length());
6670 for(int i = 0; i < r1.length(); i++) {
67 assertEquals("r1 contains alphabetic", true, Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i)));
71 assertTrue("r1 contains alphabetic", Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i)));
6872 }
6973 r2 = RandomStringUtils.randomAlphabetic(50);
7074 assertTrue("!r1.equals(r2)", !r1.equals(r2));
7276 r1 = RandomStringUtils.randomAlphanumeric(50);
7377 assertEquals("randomAlphanumeric(50)", 50, r1.length());
7478 for(int i = 0; i < r1.length(); i++) {
75 assertEquals("r1 contains alphanumeric", true, Character.isLetterOrDigit(r1.charAt(i)));
79 assertTrue("r1 contains alphanumeric", Character.isLetterOrDigit(r1.charAt(i)));
7680 }
7781 r2 = RandomStringUtils.randomAlphabetic(50);
7882 assertTrue("!r1.equals(r2)", !r1.equals(r2));
8084 r1 = RandomStringUtils.randomNumeric(50);
8185 assertEquals("randomNumeric(50)", 50, r1.length());
8286 for(int i = 0; i < r1.length(); i++) {
83 assertEquals("r1 contains numeric", true, Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i)));
87 assertTrue("r1 contains numeric", Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i)));
8488 }
8589 r2 = RandomStringUtils.randomNumeric(50);
8690 assertTrue("!r1.equals(r2)", !r1.equals(r2));
115119 assertEquals("random(50) length", 50, r2.length());
116120 assertTrue("!r1.equals(r2)", !r1.equals(r2));
117121
118 long seed = System.currentTimeMillis();
122 final long seed = System.currentTimeMillis();
119123 r1 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed));
120124 r2 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed));
121125 assertEquals("r1.equals(r2)", r1, r2);
122126
123127 r1 = RandomStringUtils.random(0);
124128 assertEquals("random(0).equals(\"\")", "", r1);
125
126 }
129 }
130
131 @Test
132 public void testLANG805() {
133 final long seed = System.currentTimeMillis();
134 assertEquals("aaa", RandomStringUtils.random(3,0,0,false,false,new char[]{'a'},new Random(seed)));
135 }
136
137 @Test
138 public void testLANG807() {
139 try {
140 RandomStringUtils.random(3,5,5,false,false);
141 fail("Expected IllegalArgumentException");
142 } catch (final IllegalArgumentException ex) { // distinguish from Random#nextInt message
143 final String msg = ex.getMessage();
144 assertTrue("Message (" + msg + ") must contain 'start'", msg.contains("start"));
145 assertTrue("Message (" + msg + ") must contain 'end'", msg.contains("end"));
146 }
147 }
148
149 @Test
127150 public void testExceptions() {
151 final char[] DUMMY = new char[]{'a'}; // valid char array
128152 try {
129153 RandomStringUtils.random(-1);
130154 fail();
131 } catch (IllegalArgumentException ex) {}
155 } catch (final IllegalArgumentException ex) {}
132156 try {
133157 RandomStringUtils.random(-1, true, true);
134158 fail();
135 } catch (IllegalArgumentException ex) {}
136 try {
137 RandomStringUtils.random(-1, new char[0]);
138 fail();
139 } catch (IllegalArgumentException ex) {}
159 } catch (final IllegalArgumentException ex) {}
160 try {
161 RandomStringUtils.random(-1, DUMMY);
162 fail();
163 } catch (final IllegalArgumentException ex) {}
164 try {
165 RandomStringUtils.random(1, new char[0]); // must not provide empty array => IAE
166 fail();
167 } catch (final IllegalArgumentException ex) {}
140168 try {
141169 RandomStringUtils.random(-1, "");
142170 fail();
143 } catch (IllegalArgumentException ex) {}
171 } catch (final IllegalArgumentException ex) {}
172 try {
173 RandomStringUtils.random(-1, (String)null);
174 fail();
175 } catch (final IllegalArgumentException ex) {}
144176 try {
145177 RandomStringUtils.random(-1, 'a', 'z', false, false);
146178 fail();
147 } catch (IllegalArgumentException ex) {}
148 try {
149 RandomStringUtils.random(-1, 'a', 'z', false, false, new char[0]);
150 fail();
151 } catch (IllegalArgumentException ex) {}
152 try {
153 RandomStringUtils.random(-1, 'a', 'z', false, false, new char[0], new Random());
154 fail();
155 } catch (IllegalArgumentException ex) {}
179 } catch (final IllegalArgumentException ex) {}
180 try {
181 RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY);
182 fail();
183 } catch (final IllegalArgumentException ex) {}
184 try {
185 RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random());
186 fail();
187 } catch (final IllegalArgumentException ex) {}
156188 }
157189
158190 /**
159191 * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric
160192 * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7
161193 */
194 @Test
162195 public void testRandomAlphaNumeric() {
163 char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'};
164 boolean[] found = {false, false, false, false, false, false};
196 final char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'};
197 final boolean[] found = {false, false, false, false, false, false};
165198 for (int i = 0; i < 100; i++) {
166 String randString = RandomStringUtils.randomAlphanumeric(10);
199 final String randString = RandomStringUtils.randomAlphanumeric(10);
167200 for (int j = 0; j < testChars.length; j++) {
168201 if (randString.indexOf(testChars[j]) > 0) {
169202 found[j] = true;
182215 * Make sure '0' and '9' are generated by randomNumeric
183216 * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46
184217 */
218 @Test
185219 public void testRandomNumeric() {
186 char[] testChars = {'0','9'};
187 boolean[] found = {false, false};
220 final char[] testChars = {'0','9'};
221 final boolean[] found = {false, false};
188222 for (int i = 0; i < 100; i++) {
189 String randString = RandomStringUtils.randomNumeric(10);
223 final String randString = RandomStringUtils.randomNumeric(10);
190224 for (int j = 0; j < testChars.length; j++) {
191225 if (randString.indexOf(testChars[j]) > 0) {
192226 found[j] = true;
205239 * Make sure boundary alpha characters are generated by randomAlphabetic
206240 * This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8
207241 */
242 @Test
208243 public void testRandomAlphabetic() {
209 char[] testChars = {'a', 'z', 'A', 'Z'};
210 boolean[] found = {false, false, false, false};
244 final char[] testChars = {'a', 'z', 'A', 'Z'};
245 final boolean[] found = {false, false, false, false};
211246 for (int i = 0; i < 100; i++) {
212 String randString = RandomStringUtils.randomAlphabetic(10);
247 final String randString = RandomStringUtils.randomAlphabetic(10);
213248 for (int j = 0; j < testChars.length; j++) {
214249 if (randString.indexOf(testChars[j]) > 0) {
215250 found[j] = true;
228263 * Make sure 32 and 127 are generated by randomNumeric
229264 * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5
230265 */
266 @Test
231267 public void testRandomAscii() {
232 char[] testChars = {(char) 32, (char) 126};
233 boolean[] found = {false, false};
268 final char[] testChars = {(char) 32, (char) 126};
269 final boolean[] found = {false, false};
234270 for (int i = 0; i < 100; i++) {
235 String randString = RandomStringUtils.randomAscii(10);
271 final String randString = RandomStringUtils.randomAscii(10);
236272 for (int j = 0; j < testChars.length; j++) {
237273 if (randString.indexOf(testChars[j]) > 0) {
238274 found[j] = true;
254290 * in generated strings. Will fail randomly about 1 in 1000 times.
255291 * Repeated failures indicate a problem.
256292 */
293 @Test
257294 public void testRandomStringUtilsHomog() {
258 String set = "abc";
259 char[] chars = set.toCharArray();
295 final String set = "abc";
296 final char[] chars = set.toCharArray();
260297 String gen = "";
261 int[] counts = {0,0,0};
262 int[] expected = {200,200,200};
298 final int[] counts = {0,0,0};
299 final int[] expected = {200,200,200};
263300 for (int i = 0; i< 100; i++) {
264301 gen = RandomStringUtils.random(6,chars);
265302 for (int j = 0; j < 6; j++) {
281318 * @param observed array of observed frequency counts
282319 * @param expected array of expected frequency counts
283320 */
284 private double chiSquare(int[] expected, int[] observed) {
321 private double chiSquare(final int[] expected, final int[] observed) {
285322 double sumSq = 0.0d;
286323 double dev = 0.0d;
287324 for (int i = 0; i < observed.length; i++) {
299336 *
300337 * @throws Exception
301338 */
339 @Test
302340 public void testLang100() throws Exception {
303 int size = 5000;
304 String encoding = "UTF-8";
305 String orig = RandomStringUtils.random(size);
306 byte[] bytes = orig.getBytes(encoding);
307 String copy = new String(bytes, encoding);
341 final int size = 5000;
342 final String encoding = "UTF-8";
343 final String orig = RandomStringUtils.random(size);
344 final byte[] bytes = orig.getBytes(encoding);
345 final String copy = new String(bytes, encoding);
308346
309347 // for a verbose compare:
310348 for (int i=0; i < orig.length() && i < copy.length(); i++) {
311 char o = orig.charAt(i);
312 char c = copy.charAt(i);
349 final char o = orig.charAt(i);
350 final char c = copy.charAt(i);
313351 assertEquals("differs at " + i + "(" + Integer.toHexString(new Character(o).hashCode()) + "," +
314352 Integer.toHexString(new Character(c).hashCode()) + ")", o, c);
315353 }
1616
1717 package org.apache.commons.lang3;
1818
19 import static org.junit.Assert.*;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertNotNull;
22 import static org.junit.Assert.assertSame;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
2025
2126 import java.util.Comparator;
2227
2833 * Tests the methods in the {@link org.apache.commons.lang3.Range} class.
2934 * </p>
3035 *
31 * @version $Id: RangeTest.java 1147537 2011-07-17 06:10:37Z mbenson $
36 * @version $Id: RangeTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3237 */
3338 @SuppressWarnings("boxing")
3439 public class RangeTest {
5964 @SuppressWarnings({ "rawtypes", "unchecked" })
6065 @Test
6166 public void testComparableConstructors() {
62 Comparable c =
67 final Comparable c =
6368 new Comparable() {
64 public int compareTo(Object other) {
69 @Override
70 public int compareTo(final Object other) {
6571 return 1;
6672 }
6773 };
68 Range r1 = Range.is(c);
69 Range r2 = Range.between(c, c);
74 final Range r1 = Range.is(c);
75 final Range r2 = Range.between(c, c);
7076 assertEquals(true, r1.isNaturalOrdering());
7177 assertEquals(true, r2.isNaturalOrdering());
7278 }
7379
7480 @Test
7581 public void testIsWithCompare(){
76 Comparator<Integer> c = new Comparator<Integer>(){
77 public int compare(Integer o1, Integer o2) {
82 final Comparator<Integer> c = new Comparator<Integer>(){
83 @Override
84 public int compare(final Integer o1, final Integer o2) {
7885 return 0; // all integers are equal
7986 }
8087 };
9198 @Test
9299 public void testBetweenWithCompare(){
93100 // TODO add tests with a better comparator
94 Comparator<Integer> c = new Comparator<Integer>(){
95 public int compare(Integer o1, Integer o2) {
101 final Comparator<Integer> c = new Comparator<Integer>(){
102 @Override
103 public int compare(final Integer o1, final Integer o2) {
96104 return 0; // all integers are equal
97105 }
98106 };
113121 //-----------------------------------------------------------------------
114122 @Test
115123 public void testRangeOfChars() {
116 Range<Character> chars = Range.between('a', 'z');
124 final Range<Character> chars = Range.between('a', 'z');
117125 assertTrue(chars.contains('b'));
118126 assertFalse(chars.contains('B'));
119127 }
145153 public void testToString() {
146154 assertNotNull(byteRange.toString());
147155
148 String str = intRange.toString();
156 final String str = intRange.toString();
149157 assertEquals("[10..20]", str);
150158 assertEquals("[-20..-10]", Range.between(-20, -10).toString());
151159 }
152160
153161 @Test
154162 public void testToStringFormat() {
155 String str = intRange.toString("From %1$s to %2$s");
163 final String str = intRange.toString("From %1$s to %2$s");
156164 assertEquals("From 10 to 20", str);
157165 }
158166
233241 try {
234242 intRange.elementCompareTo(null);
235243 fail("NullPointerException should have been thrown");
236 } catch(NullPointerException npe) {
244 } catch(final NullPointerException npe) {
237245 // expected
238246 }
239247
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertNull;
22 import static org.junit.Assert.assertSame;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
1826 import java.io.ByteArrayInputStream;
1927 import java.io.ByteArrayOutputStream;
2028 import java.io.IOException;
2735 import java.lang.reflect.Modifier;
2836 import java.util.HashMap;
2937
30 import junit.framework.TestCase;
38 import org.junit.Assert;
39 import org.junit.Before;
40 import org.junit.Test;
3141
3242 /**
3343 * Unit tests {@link org.apache.commons.lang3.SerializationUtils}.
3444 *
35 * @version $Id: SerializationUtilsTest.java 1153484 2011-08-03 13:39:42Z ggregory $
45 * @version $Id: SerializationUtilsTest.java 1553926 2013-12-28 21:15:10Z ggregory $
3646 */
37 public class SerializationUtilsTest extends TestCase {
47 public class SerializationUtilsTest {
3848
3949 static final String CLASS_NOT_FOUND_MESSAGE = "ClassNotFoundSerialization.readObject fake exception";
4050 protected static final String SERIALIZE_IO_EXCEPTION_MESSAGE = "Anonymous OutputStream I/O exception";
4353 private Integer iInteger;
4454 private HashMap<Object, Object> iMap;
4555
46 public SerializationUtilsTest(String name) {
47 super(name);
48 }
49
50 @Override
51 protected void setUp() throws Exception {
52 super.setUp();
53
56 @Before
57 public void setUp() {
5458 iString = "foo";
5559 iInteger = Integer.valueOf(7);
5660 iMap = new HashMap<Object, Object>();
5963 }
6064
6165 //-----------------------------------------------------------------------
66
67 @Test
6268 public void testConstructor() {
6369 assertNotNull(new SerializationUtils());
64 Constructor<?>[] cons = SerializationUtils.class.getDeclaredConstructors();
70 final Constructor<?>[] cons = SerializationUtils.class.getDeclaredConstructors();
6571 assertEquals(1, cons.length);
66 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
67 assertEquals(true, Modifier.isPublic(SerializationUtils.class.getModifiers()));
68 assertEquals(false, Modifier.isFinal(SerializationUtils.class.getModifiers()));
72 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
73 assertTrue(Modifier.isPublic(SerializationUtils.class.getModifiers()));
74 assertFalse(Modifier.isFinal(SerializationUtils.class.getModifiers()));
6975 }
7076
77 @Test
7178 public void testException() {
7279 SerializationException serEx;
73 Exception ex = new Exception();
80 final Exception ex = new Exception();
7481
7582 serEx = new SerializationException();
7683 assertSame(null, serEx.getMessage());
9097 }
9198
9299 //-----------------------------------------------------------------------
100
101 @Test
93102 public void testSerializeStream() throws Exception {
94 ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
103 final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
95104 SerializationUtils.serialize(iMap, streamTest);
96105
97 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
98 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
106 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
107 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
99108 oos.writeObject(iMap);
100109 oos.flush();
101110 oos.close();
102111
103 byte[] testBytes = streamTest.toByteArray();
104 byte[] realBytes = streamReal.toByteArray();
112 final byte[] testBytes = streamTest.toByteArray();
113 final byte[] realBytes = streamReal.toByteArray();
105114 assertEquals(testBytes.length, realBytes.length);
106115 for (int i = 0; i < realBytes.length; i++) {
107116 assertEquals(realBytes[i], testBytes[i]);
108117 }
109118 }
110119
120 @Test
111121 public void testSerializeStreamUnserializable() throws Exception {
112 ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
122 final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
113123 try {
114124 iMap.put(new Object(), new Object());
115125 SerializationUtils.serialize(iMap, streamTest);
116 } catch (SerializationException ex) {
117 return;
118 }
119 fail();
120 }
121
126 } catch (final SerializationException ex) {
127 return;
128 }
129 fail();
130 }
131
132 @Test
122133 public void testSerializeStreamNullObj() throws Exception {
123 ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
134 final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
124135 SerializationUtils.serialize(null, streamTest);
125136
126 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
127 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
137 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
138 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
128139 oos.writeObject(null);
129140 oos.flush();
130141 oos.close();
131142
132 byte[] testBytes = streamTest.toByteArray();
133 byte[] realBytes = streamReal.toByteArray();
143 final byte[] testBytes = streamTest.toByteArray();
144 final byte[] realBytes = streamReal.toByteArray();
134145 assertEquals(testBytes.length, realBytes.length);
135146 for (int i = 0; i < realBytes.length; i++) {
136147 assertEquals(realBytes[i], testBytes[i]);
137148 }
138149 }
139150
151 @Test
140152 public void testSerializeStreamObjNull() throws Exception {
141153 try {
142154 SerializationUtils.serialize(iMap, null);
143 } catch (IllegalArgumentException ex) {
144 return;
145 }
146 fail();
147 }
148
155 } catch (final IllegalArgumentException ex) {
156 return;
157 }
158 fail();
159 }
160
161 @Test
149162 public void testSerializeStreamNullNull() throws Exception {
150163 try {
151164 SerializationUtils.serialize(null, null);
152 } catch (IllegalArgumentException ex) {
165 } catch (final IllegalArgumentException ex) {
153166 return;
154167 }
155168 fail();
156169 }
157170
171 @Test
158172 public void testSerializeIOException() throws Exception {
159173 // forces an IOException when the ObjectOutputStream is created, to test not closing the stream
160174 // in the finally block
161 OutputStream streamTest = new OutputStream() {
175 final OutputStream streamTest = new OutputStream() {
162176 @Override
163 public void write(int arg0) throws IOException {
177 public void write(final int arg0) throws IOException {
164178 throw new IOException(SERIALIZE_IO_EXCEPTION_MESSAGE);
165179 }
166180 };
167181 try {
168182 SerializationUtils.serialize(iMap, streamTest);
169183 }
170 catch(SerializationException e) {
184 catch(final SerializationException e) {
171185 assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
172186 }
173187 }
174188
175189 //-----------------------------------------------------------------------
176190
191 @Test
177192 public void testDeserializeStream() throws Exception {
178 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
179 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
193 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
194 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
180195 oos.writeObject(iMap);
181196 oos.flush();
182197 oos.close();
183198
184 ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
185 Object test = SerializationUtils.deserialize(inTest);
199 final ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
200 final Object test = SerializationUtils.deserialize(inTest);
186201 assertNotNull(test);
187202 assertTrue(test instanceof HashMap<?, ?>);
188203 assertTrue(test != iMap);
189 HashMap<?, ?> testMap = (HashMap<?, ?>) test;
204 final HashMap<?, ?> testMap = (HashMap<?, ?>) test;
190205 assertEquals(iString, testMap.get("FOO"));
191206 assertTrue(iString != testMap.get("FOO"));
192207 assertEquals(iInteger, testMap.get("BAR"));
194209 assertEquals(iMap, testMap);
195210 }
196211
212 @Test(expected=ClassCastException.class)
213 public void testDeserializeClassCastException() {
214 final String value = "Hello";
215 final byte[] serialized = SerializationUtils.serialize(value);
216 Assert.assertEquals(value, SerializationUtils.deserialize(serialized));
217 // Causes ClassCastException in call site, not in SerializationUtils.deserialize
218 @SuppressWarnings("unused") // needed to cause Exception
219 final Integer i = SerializationUtils.deserialize(serialized);
220 }
221
222 @Test
197223 public void testDeserializeStreamOfNull() throws Exception {
198 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
199 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
224 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
225 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
200226 oos.writeObject(null);
201227 oos.flush();
202228 oos.close();
203229
204 ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
205 Object test = SerializationUtils.deserialize(inTest);
230 final ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
231 final Object test = SerializationUtils.deserialize(inTest);
206232 assertNull(test);
207233 }
208234
235 @Test
209236 public void testDeserializeStreamNull() throws Exception {
210237 try {
211238 SerializationUtils.deserialize((InputStream) null);
212 } catch (IllegalArgumentException ex) {
213 return;
214 }
215 fail();
216 }
217
239 } catch (final IllegalArgumentException ex) {
240 return;
241 }
242 fail();
243 }
244
245 @Test
218246 public void testDeserializeStreamBadStream() throws Exception {
219247 try {
220248 SerializationUtils.deserialize(new ByteArrayInputStream(new byte[0]));
221 } catch (SerializationException ex) {
222 return;
223 }
224 fail();
225 }
226
249 } catch (final SerializationException ex) {
250 return;
251 }
252 fail();
253 }
254
255 @Test
227256 public void testDeserializeStreamClassNotFound() throws Exception {
228 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
229 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
257 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
258 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
230259 oos.writeObject(new ClassNotFoundSerialization());
231260 oos.flush();
232261 oos.close();
233262
234 ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
263 final ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
235264 try {
236265 @SuppressWarnings("unused")
266 final
237267 Object test = SerializationUtils.deserialize(inTest);
238 } catch(SerializationException se) {
268 } catch(final SerializationException se) {
239269 assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage());
240270 }
241271 }
242272
243273 //-----------------------------------------------------------------------
244274
275 @Test
245276 public void testSerializeBytes() throws Exception {
246 byte[] testBytes = SerializationUtils.serialize(iMap);
247
248 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
249 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
277 final byte[] testBytes = SerializationUtils.serialize(iMap);
278
279 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
280 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
250281 oos.writeObject(iMap);
251282 oos.flush();
252283 oos.close();
253284
254 byte[] realBytes = streamReal.toByteArray();
285 final byte[] realBytes = streamReal.toByteArray();
255286 assertEquals(testBytes.length, realBytes.length);
256287 for (int i = 0; i < realBytes.length; i++) {
257288 assertEquals(realBytes[i], testBytes[i]);
258289 }
259290 }
260291
292 @Test
261293 public void testSerializeBytesUnserializable() throws Exception {
262294 try {
263295 iMap.put(new Object(), new Object());
264296 SerializationUtils.serialize(iMap);
265 } catch (SerializationException ex) {
266 return;
267 }
268 fail();
269 }
270
297 } catch (final SerializationException ex) {
298 return;
299 }
300 fail();
301 }
302
303 @Test
271304 public void testSerializeBytesNull() throws Exception {
272 byte[] testBytes = SerializationUtils.serialize(null);
273
274 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
275 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
305 final byte[] testBytes = SerializationUtils.serialize(null);
306
307 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
308 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
276309 oos.writeObject(null);
277310 oos.flush();
278311 oos.close();
279312
280 byte[] realBytes = streamReal.toByteArray();
313 final byte[] realBytes = streamReal.toByteArray();
281314 assertEquals(testBytes.length, realBytes.length);
282315 for (int i = 0; i < realBytes.length; i++) {
283316 assertEquals(realBytes[i], testBytes[i]);
286319
287320 //-----------------------------------------------------------------------
288321
322 @Test
289323 public void testDeserializeBytes() throws Exception {
290 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
291 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
324 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
325 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
292326 oos.writeObject(iMap);
293327 oos.flush();
294328 oos.close();
295329
296 Object test = SerializationUtils.deserialize(streamReal.toByteArray());
330 final Object test = SerializationUtils.deserialize(streamReal.toByteArray());
297331 assertNotNull(test);
298332 assertTrue(test instanceof HashMap<?, ?>);
299333 assertTrue(test != iMap);
300 HashMap<?, ?> testMap = (HashMap<?, ?>) test;
334 final HashMap<?, ?> testMap = (HashMap<?, ?>) test;
301335 assertEquals(iString, testMap.get("FOO"));
302336 assertTrue(iString != testMap.get("FOO"));
303337 assertEquals(iInteger, testMap.get("BAR"));
305339 assertEquals(iMap, testMap);
306340 }
307341
342 @Test
308343 public void testDeserializeBytesOfNull() throws Exception {
309 ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
310 ObjectOutputStream oos = new ObjectOutputStream(streamReal);
344 final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
345 final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
311346 oos.writeObject(null);
312347 oos.flush();
313348 oos.close();
314349
315 Object test = SerializationUtils.deserialize(streamReal.toByteArray());
350 final Object test = SerializationUtils.deserialize(streamReal.toByteArray());
316351 assertNull(test);
317352 }
318353
354 @Test
319355 public void testDeserializeBytesNull() throws Exception {
320356 try {
321357 SerializationUtils.deserialize((byte[]) null);
322 } catch (IllegalArgumentException ex) {
323 return;
324 }
325 fail();
326 }
327
358 } catch (final IllegalArgumentException ex) {
359 return;
360 }
361 fail();
362 }
363
364 @Test
328365 public void testDeserializeBytesBadStream() throws Exception {
329366 try {
330367 SerializationUtils.deserialize(new byte[0]);
331 } catch (SerializationException ex) {
332 return;
333 }
334 fail();
335 }
336
337 //-----------------------------------------------------------------------
338
368 } catch (final SerializationException ex) {
369 return;
370 }
371 fail();
372 }
373
374 //-----------------------------------------------------------------------
375
376 @Test
339377 public void testClone() throws Exception {
340 Object test = SerializationUtils.clone(iMap);
378 final Object test = SerializationUtils.clone(iMap);
341379 assertNotNull(test);
342380 assertTrue(test instanceof HashMap<?,?>);
343381 assertTrue(test != iMap);
344 HashMap<?, ?> testMap = (HashMap<?, ?>) test;
382 final HashMap<?, ?> testMap = (HashMap<?, ?>) test;
345383 assertEquals(iString, testMap.get("FOO"));
346384 assertTrue(iString != testMap.get("FOO"));
347385 assertEquals(iInteger, testMap.get("BAR"));
349387 assertEquals(iMap, testMap);
350388 }
351389
390 @Test
352391 public void testCloneNull() throws Exception {
353 Object test = SerializationUtils.clone(null);
392 final Object test = SerializationUtils.clone(null);
354393 assertNull(test);
355394 }
356395
396 @Test
357397 public void testCloneUnserializable() throws Exception {
358398 try {
359399 iMap.put(new Object(), new Object());
360400 SerializationUtils.clone(iMap);
361 } catch (SerializationException ex) {
362 return;
363 }
364 fail();
401 } catch (final SerializationException ex) {
402 return;
403 }
404 fail();
405 }
406
407 @Test
408 public void testPrimitiveTypeClassSerialization() {
409 final Class<?>[] primitiveTypes = { byte.class, short.class, int.class, long.class, float.class, double.class,
410 boolean.class, char.class, void.class };
411
412 for (final Class<?> primitiveType : primitiveTypes) {
413 final Class<?> clone = SerializationUtils.clone(primitiveType);
414 assertEquals(primitiveType, clone);
415 }
365416 }
366417
367418 }
370421 class ClassNotFoundSerialization implements Serializable
371422 {
372423
373 private void readObject(ObjectInputStream in) throws ClassNotFoundException {
424 private static final long serialVersionUID = 1L;
425
426 private void readObject(final ObjectInputStream in) throws ClassNotFoundException {
374427 throw new ClassNotFoundException(SerializationUtilsTest.CLASS_NOT_FOUND_MESSAGE);
375428 }
376429 }
2828 import java.lang.reflect.Modifier;
2929
3030 import org.apache.commons.io.IOUtils;
31 import org.junit.Test;
32
3331 import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
3432 import org.apache.commons.lang3.text.translate.NumericEntityEscaper;
33 import org.junit.Test;
3534
3635 /**
3736 * Unit tests for {@link StringEscapeUtils}.
3837 *
39 * @version $Id: StringEscapeUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
38 * @version $Id: StringEscapeUtilsTest.java 1553930 2013-12-28 21:22:41Z ggregory $
4039 */
4140 public class StringEscapeUtilsTest {
4241 private final static String FOO = "foo";
4443 @Test
4544 public void testConstructor() {
4645 assertNotNull(new StringEscapeUtils());
47 Constructor<?>[] cons = StringEscapeUtils.class.getDeclaredConstructors();
46 final Constructor<?>[] cons = StringEscapeUtils.class.getDeclaredConstructors();
4847 assertEquals(1, cons.length);
4948 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
5049 assertTrue(Modifier.isPublic(StringEscapeUtils.class.getModifiers()));
5756 try {
5857 StringEscapeUtils.ESCAPE_JAVA.translate(null, null);
5958 fail();
60 } catch (IOException ex) {
61 fail();
62 } catch (IllegalArgumentException ex) {
59 } catch (final IOException ex) {
60 fail();
61 } catch (final IllegalArgumentException ex) {
6362 }
6463 try {
6564 StringEscapeUtils.ESCAPE_JAVA.translate("", null);
6665 fail();
67 } catch (IOException ex) {
68 fail();
69 } catch (IllegalArgumentException ex) {
66 } catch (final IOException ex) {
67 fail();
68 } catch (final IllegalArgumentException ex) {
7069 }
7170
7271 assertEscapeJava("empty string", "", "");
106105 assertEquals(expected, actual);
107106 }
108107
109 private void assertEscapeJava(String escaped, String original) throws IOException {
108 private void assertEscapeJava(final String escaped, final String original) throws IOException {
110109 assertEscapeJava(null, escaped, original);
111110 }
112111
113 private void assertEscapeJava(String message, String expected, String original) throws IOException {
114 String converted = StringEscapeUtils.escapeJava(original);
112 private void assertEscapeJava(String message, final String expected, final String original) throws IOException {
113 final String converted = StringEscapeUtils.escapeJava(original);
115114 message = "escapeJava(String) failed" + (message == null ? "" : (": " + message));
116115 assertEquals(message, expected, converted);
117116
118 StringWriter writer = new StringWriter();
117 final StringWriter writer = new StringWriter();
119118 StringEscapeUtils.ESCAPE_JAVA.translate(original, writer);
120119 assertEquals(expected, writer.toString());
121120 }
126125 try {
127126 StringEscapeUtils.UNESCAPE_JAVA.translate(null, null);
128127 fail();
129 } catch (IOException ex) {
130 fail();
131 } catch (IllegalArgumentException ex) {
128 } catch (final IOException ex) {
129 fail();
130 } catch (final IllegalArgumentException ex) {
132131 }
133132 try {
134133 StringEscapeUtils.UNESCAPE_JAVA.translate("", null);
135134 fail();
136 } catch (IOException ex) {
137 fail();
138 } catch (IllegalArgumentException ex) {
135 } catch (final IOException ex) {
136 fail();
137 } catch (final IllegalArgumentException ex) {
139138 }
140139 try {
141140 StringEscapeUtils.unescapeJava("\\u02-3");
142141 fail();
143 } catch (RuntimeException ex) {
142 } catch (final RuntimeException ex) {
144143 }
145144
146145 assertUnescapeJava("", "");
155154 assertUnescapeJava("Unicode as final character", "\uABCD", "\\uabcd");
156155 }
157156
158 private void assertUnescapeJava(String unescaped, String original) throws IOException {
157 private void assertUnescapeJava(final String unescaped, final String original) throws IOException {
159158 assertUnescapeJava(null, unescaped, original);
160159 }
161160
162 private void assertUnescapeJava(String message, String unescaped, String original) throws IOException {
163 String expected = unescaped;
164 String actual = StringEscapeUtils.unescapeJava(original);
161 private void assertUnescapeJava(final String message, final String unescaped, final String original) throws IOException {
162 final String expected = unescaped;
163 final String actual = StringEscapeUtils.unescapeJava(original);
165164
166165 assertEquals("unescape(String) failed" +
167166 (message == null ? "" : (": " + message)) +
170169 "' actual '" + StringEscapeUtils.escapeJava(actual) + "'",
171170 expected, actual);
172171
173 StringWriter writer = new StringWriter();
172 final StringWriter writer = new StringWriter();
174173 StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer);
175174 assertEquals(unescaped, writer.toString());
176175
182181 try {
183182 StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null);
184183 fail();
185 } catch (IOException ex) {
186 fail();
187 } catch (IllegalArgumentException ex) {
184 } catch (final IOException ex) {
185 fail();
186 } catch (final IllegalArgumentException ex) {
188187 }
189188 try {
190189 StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null);
191190 fail();
192 } catch (IOException ex) {
193 fail();
194 } catch (IllegalArgumentException ex) {
191 } catch (final IOException ex) {
192 fail();
193 } catch (final IllegalArgumentException ex) {
195194 }
196195
197196 assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeEcmaScript("He didn't say, \"stop!\""));
219218
220219 @Test
221220 public void testEscapeHtml() {
222 for (int i = 0; i < HTML_ESCAPES.length; ++i) {
223 String message = HTML_ESCAPES[i][0];
224 String expected = HTML_ESCAPES[i][1];
225 String original = HTML_ESCAPES[i][2];
221 for (String[] element : HTML_ESCAPES) {
222 final String message = element[0];
223 final String expected = element[1];
224 final String original = element[2];
226225 assertEquals(message, expected, StringEscapeUtils.escapeHtml4(original));
227 StringWriter sw = new StringWriter();
226 final StringWriter sw = new StringWriter();
228227 try {
229228 StringEscapeUtils.ESCAPE_HTML4.translate(original, sw);
230 } catch (IOException e) {
229 } catch (final IOException e) {
231230 }
232 String actual = original == null ? null : sw.toString();
231 final String actual = original == null ? null : sw.toString();
233232 assertEquals(message, expected, actual);
234233 }
235234 }
236235
237236 @Test
238237 public void testUnescapeHtml4() {
239 for (int i = 0; i < HTML_ESCAPES.length; ++i) {
240 String message = HTML_ESCAPES[i][0];
241 String expected = HTML_ESCAPES[i][2];
242 String original = HTML_ESCAPES[i][1];
238 for (String[] element : HTML_ESCAPES) {
239 final String message = element[0];
240 final String expected = element[2];
241 final String original = element[1];
243242 assertEquals(message, expected, StringEscapeUtils.unescapeHtml4(original));
244243
245 StringWriter sw = new StringWriter();
244 final StringWriter sw = new StringWriter();
246245 try {
247246 StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw);
248 } catch (IOException e) {
247 } catch (final IOException e) {
249248 }
250 String actual = original == null ? null : sw.toString();
249 final String actual = original == null ? null : sw.toString();
251250 assertEquals(message, expected, actual);
252251 }
253252 // \u00E7 is a cedilla (c with wiggle under)
268267 assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("&#X80;&#X9F;"));
269268 // Test all Character values:
270269 for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
271 Character c1 = new Character(i);
272 Character c2 = new Character((char)(i+1));
273 String expected = c1.toString() + c2.toString();
274 String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";";
275 String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";";
270 final Character c1 = new Character(i);
271 final Character c2 = new Character((char)(i+1));
272 final String expected = c1.toString() + c2.toString();
273 final String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";";
274 final String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";";
276275 assertEquals("hex number unescape index " + (int)i, expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2));
277276 }
278277 }
315314 StringWriter sw = new StringWriter();
316315 try {
317316 StringEscapeUtils.ESCAPE_XML.translate("<abc>", sw);
318 } catch (IOException e) {
317 } catch (final IOException e) {
319318 }
320319 assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() );
321320
322321 sw = new StringWriter();
323322 try {
324323 StringEscapeUtils.UNESCAPE_XML.translate("&lt;abc&gt;", sw);
325 } catch (IOException e) {
324 } catch (final IOException e) {
326325 }
327326 assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() );
328327 }
343342 */
344343 @Test
345344 public void testEscapeXmlSupplementaryCharacters() {
346 CharSequenceTranslator escapeXml =
345 final CharSequenceTranslator escapeXml =
347346 StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );
348347
349348 assertEquals("Supplementary character must be represented using a single escape", "&#144308;",
350349 escapeXml.translate("\uD84C\uDFB4"));
350 }
351
352 @Test
353 public void testEscapeXmlAllCharacters() {
354 // http://www.w3.org/TR/xml/#charsets says:
355 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character,
356 // excluding the surrogate blocks, FFFE, and FFFF. */
357 final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML
358 .with(NumericEntityEscaper.below(9), NumericEntityEscaper.between(0xB, 0xC), NumericEntityEscaper.between(0xE, 0x19),
359 NumericEntityEscaper.between(0xD800, 0xDFFF), NumericEntityEscaper.between(0xFFFE, 0xFFFF), NumericEntityEscaper.above(0x110000));
360
361 assertEquals("&#0;&#1;&#2;&#3;&#4;&#5;&#6;&#7;&#8;", escapeXml.translate("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008"));
362 assertEquals("\t", escapeXml.translate("\t")); // 0x9
363 assertEquals("\n", escapeXml.translate("\n")); // 0xA
364 assertEquals("&#11;&#12;", escapeXml.translate("\u000B\u000C"));
365 assertEquals("\r", escapeXml.translate("\r")); // 0xD
366 assertEquals("Hello World! Ain&apos;t this great?", escapeXml.translate("Hello World! Ain't this great?"));
367 assertEquals("&#14;&#15;&#24;&#25;", escapeXml.translate("\u000E\u000F\u0018\u0019"));
351368 }
352369
353370 /**
360377 assertEquals("Supplementary character must be represented using a single escape", "\uD84C\uDFB4",
361378 StringEscapeUtils.unescapeXml("&#144308;") );
362379 }
363
380
364381 // Tests issue #38569
365382 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569
366383 @Test
398415 checkCsvEscapeWriter("", "");
399416 }
400417
401 private void checkCsvEscapeWriter(String expected, String value) {
402 try {
403 StringWriter writer = new StringWriter();
418 private void checkCsvEscapeWriter(final String expected, final String value) {
419 try {
420 final StringWriter writer = new StringWriter();
404421 StringEscapeUtils.ESCAPE_CSV.translate(value, writer);
405422 assertEquals(expected, writer.toString());
406 } catch (IOException e) {
423 } catch (final IOException e) {
407424 fail("Threw: " + e);
408425 }
409426 }
434451 checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\"");
435452 }
436453
437 private void checkCsvUnescapeWriter(String expected, String value) {
438 try {
439 StringWriter writer = new StringWriter();
454 private void checkCsvUnescapeWriter(final String expected, final String value) {
455 try {
456 final StringWriter writer = new StringWriter();
440457 StringEscapeUtils.UNESCAPE_CSV.translate(value, writer);
441458 assertEquals(expected, writer.toString());
442 } catch (IOException e) {
459 } catch (final IOException e) {
443460 fail("Threw: " + e);
444461 }
445462 }
455472 // COUNTING ROD UNIT DIGIT THREE
456473 // in Unicode
457474 // codepoint: U+1D362
458 byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 };
459
460 String original = new String(data, "UTF8");
461
462 String escaped = StringEscapeUtils.escapeHtml4( original );
475 final byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 };
476
477 final String original = new String(data, "UTF8");
478
479 final String escaped = StringEscapeUtils.escapeHtml4( original );
463480 assertEquals( "High Unicode should not have been escaped", original, escaped);
464481
465 String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
482 final String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
466483 assertEquals( "High Unicode should have been unchanged", original, unescaped);
467484
468485 // TODO: I think this should hold, needs further investigation
476493 @Test
477494 public void testEscapeHiragana() {
478495 // Some random Japanese Unicode characters
479 String original = "\u304B\u304C\u3068";
480 String escaped = StringEscapeUtils.escapeHtml4(original);
496 final String original = "\u304B\u304C\u3068";
497 final String escaped = StringEscapeUtils.escapeHtml4(original);
481498 assertEquals( "Hiragana character Unicode behaviour should not be being escaped by escapeHtml4",
482499 original, escaped);
483500
484 String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
501 final String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
485502
486503 assertEquals( "Hiragana character Unicode behaviour has changed - expected no unescaping", escaped, unescaped);
487504 }
494511 */
495512 @Test
496513 public void testLang708() throws IOException {
497 String input = IOUtils.toString(new FileInputStream("src/test/resources/lang-708-input.txt"), "UTF-8");
498 String escaped = StringEscapeUtils.escapeEcmaScript(input);
514 final String input = IOUtils.toString(new FileInputStream("src/test/resources/lang-708-input.txt"), "UTF-8");
515 final String escaped = StringEscapeUtils.escapeEcmaScript(input);
499516 // just the end:
500517 assertTrue(escaped, escaped.endsWith("}]"));
501518 // a little more:
507524 */
508525 @Test
509526 public void testLang720() {
510 String input = new StringBuilder("\ud842\udfb7").append("A").toString();
511 String escaped = StringEscapeUtils.escapeXml(input);
527 final String input = new StringBuilder("\ud842\udfb7").append("A").toString();
528 final String escaped = StringEscapeUtils.escapeXml(input);
512529 assertEquals(input, escaped);
513530 }
531
532 /**
533 * Tests https://issues.apache.org/jira/browse/LANG-911
534 */
535 @Test
536 public void testLang911() {
537 String bellsTest = "\ud83d\udc80\ud83d\udd14";
538 String value = StringEscapeUtils.escapeJava(bellsTest);
539 String valueTest = StringEscapeUtils.unescapeJava(value);
540 assertEquals(bellsTest, valueTest);
541 }
542
543 @Test
544 public void testEscapeJson() {
545 assertEquals(null, StringEscapeUtils.escapeJson(null));
546 try {
547 StringEscapeUtils.ESCAPE_JSON.translate(null, null);
548 fail();
549 } catch (final IOException ex) {
550 fail();
551 } catch (final IllegalArgumentException ex) {
552 }
553 try {
554 StringEscapeUtils.ESCAPE_JSON.translate("", null);
555 fail();
556 } catch (final IOException ex) {
557 fail();
558 } catch (final IllegalArgumentException ex) {
559 }
560
561 assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\""));
562
563 String expected = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/";
564 String input ="\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/";
565
566 assertEquals(expected, StringEscapeUtils.escapeJson(input));
567 }
568
514569 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertThat;
21 import static org.junit.Assert.assertTrue;
22
1823 import java.util.Locale;
1924
20 import junit.framework.TestCase;
25 import org.hamcrest.core.IsNot;
26 import org.junit.Test;
2127
2228 /**
2329 * Unit tests {@link org.apache.commons.lang3.StringUtils} - Substring methods
2430 *
25 * @version $Id: StringUtilsEqualsIndexOfTest.java 1144929 2011-07-10 18:26:16Z ggregory $
31 * @version $Id: StringUtilsEqualsIndexOfTest.java 1493144 2013-06-14 16:19:27Z sebb $
2632 */
27 public class StringUtilsEqualsIndexOfTest extends TestCase {
33 public class StringUtilsEqualsIndexOfTest {
2834 private static final String BAR = "bar";
2935 /**
3036 * Supplementary character U+20000
31 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
37 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
3238 */
3339 private static final String CharU20000 = "\uD840\uDC00";
3440 /**
3541 * Supplementary character U+20001
36 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
42 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
3743 */
3844 private static final String CharU20001 = "\uD840\uDC01";
3945 /**
4046 * Incomplete supplementary character U+20000, high surrogate only.
41 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
47 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
4248 */
4349 private static final String CharUSuppCharHigh = "\uDC00";
4450
4551 /**
4652 * Incomplete supplementary character U+20000, low surrogate only.
47 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
53 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
4854 */
4955 private static final String CharUSuppCharLow = "\uD840";
5056
5460
5561 private static final String[] FOOBAR_SUB_ARRAY = new String[] {"ob", "ba"};
5662
57 public StringUtilsEqualsIndexOfTest(String name) {
58 super(name);
59 }
60
63 @Test
6164 public void testContains_Char() {
62 assertEquals(false, StringUtils.contains(null, ' '));
63 assertEquals(false, StringUtils.contains("", ' '));
64 assertEquals(false, StringUtils.contains("", null));
65 assertEquals(false, StringUtils.contains(null, null));
66 assertEquals(true, StringUtils.contains("abc", 'a'));
67 assertEquals(true, StringUtils.contains("abc", 'b'));
68 assertEquals(true, StringUtils.contains("abc", 'c'));
69 assertEquals(false, StringUtils.contains("abc", 'z'));
70 }
71
65 assertFalse(StringUtils.contains(null, ' '));
66 assertFalse(StringUtils.contains("", ' '));
67 assertFalse(StringUtils.contains("", null));
68 assertFalse(StringUtils.contains(null, null));
69 assertTrue(StringUtils.contains("abc", 'a'));
70 assertTrue(StringUtils.contains("abc", 'b'));
71 assertTrue(StringUtils.contains("abc", 'c'));
72 assertFalse(StringUtils.contains("abc", 'z'));
73 }
74
75 @Test
7276 public void testContains_String() {
73 assertEquals(false, StringUtils.contains(null, null));
74 assertEquals(false, StringUtils.contains(null, ""));
75 assertEquals(false, StringUtils.contains(null, "a"));
76 assertEquals(false, StringUtils.contains("", null));
77 assertEquals(true, StringUtils.contains("", ""));
78 assertEquals(false, StringUtils.contains("", "a"));
79 assertEquals(true, StringUtils.contains("abc", "a"));
80 assertEquals(true, StringUtils.contains("abc", "b"));
81 assertEquals(true, StringUtils.contains("abc", "c"));
82 assertEquals(true, StringUtils.contains("abc", "abc"));
83 assertEquals(false, StringUtils.contains("abc", "z"));
84 }
85
86 /**
87 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
88 */
77 assertFalse(StringUtils.contains(null, null));
78 assertFalse(StringUtils.contains(null, ""));
79 assertFalse(StringUtils.contains(null, "a"));
80 assertFalse(StringUtils.contains("", null));
81 assertTrue(StringUtils.contains("", ""));
82 assertFalse(StringUtils.contains("", "a"));
83 assertTrue(StringUtils.contains("abc", "a"));
84 assertTrue(StringUtils.contains("abc", "b"));
85 assertTrue(StringUtils.contains("abc", "c"));
86 assertTrue(StringUtils.contains("abc", "abc"));
87 assertFalse(StringUtils.contains("abc", "z"));
88 }
89
90 /**
91 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
92 */
93 @Test
8994 public void testContains_StringWithBadSupplementaryChars() {
9095 // Test edge case: 1/2 of a (broken) supplementary char
91 assertEquals(false, StringUtils.contains(CharUSuppCharHigh, CharU20001));
92 assertEquals(false, StringUtils.contains(CharUSuppCharLow, CharU20001));
93 assertEquals(false, StringUtils.contains(CharU20001, CharUSuppCharHigh));
96 assertFalse(StringUtils.contains(CharUSuppCharHigh, CharU20001));
97 assertFalse(StringUtils.contains(CharUSuppCharLow, CharU20001));
98 assertFalse(StringUtils.contains(CharU20001, CharUSuppCharHigh));
9499 assertEquals(0, CharU20001.indexOf(CharUSuppCharLow));
95 assertEquals(true, StringUtils.contains(CharU20001, CharUSuppCharLow));
96 assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharLow + "a", "a"));
97 assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharHigh + "a", "a"));
98 }
99
100 /**
101 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
102 */
100 assertTrue(StringUtils.contains(CharU20001, CharUSuppCharLow));
101 assertTrue(StringUtils.contains(CharU20001 + CharUSuppCharLow + "a", "a"));
102 assertTrue(StringUtils.contains(CharU20001 + CharUSuppCharHigh + "a", "a"));
103 }
104
105 /**
106 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
107 */
108 @Test
103109 public void testContains_StringWithSupplementaryChars() {
104 assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20000));
105 assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20001));
106 assertEquals(true, StringUtils.contains(CharU20000, CharU20000));
107 assertEquals(false, StringUtils.contains(CharU20000, CharU20001));
108 }
109
110 assertTrue(StringUtils.contains(CharU20000 + CharU20001, CharU20000));
111 assertTrue(StringUtils.contains(CharU20000 + CharU20001, CharU20001));
112 assertTrue(StringUtils.contains(CharU20000, CharU20000));
113 assertFalse(StringUtils.contains(CharU20000, CharU20001));
114 }
115
116 @Test
110117 public void testContainsAny_StringCharArray() {
111118 assertFalse(StringUtils.containsAny(null, (char[]) null));
112119 assertFalse(StringUtils.containsAny(null, new char[0]));
124131 }
125132
126133 /**
127 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
128 */
134 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
135 */
136 @Test
129137 public void testContainsAny_StringCharArrayWithBadSupplementaryChars() {
130138 // Test edge case: 1/2 of a (broken) supplementary char
131 assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001.toCharArray()));
132 assertEquals(false, StringUtils.containsAny("abc" + CharUSuppCharHigh + "xyz", CharU20001.toCharArray()));
139 assertFalse(StringUtils.containsAny(CharUSuppCharHigh, CharU20001.toCharArray()));
140 assertFalse(StringUtils.containsAny("abc" + CharUSuppCharHigh + "xyz", CharU20001.toCharArray()));
133141 assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001));
134 assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001.toCharArray()));
135 assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh.toCharArray()));
142 assertFalse(StringUtils.containsAny(CharUSuppCharLow, CharU20001.toCharArray()));
143 assertFalse(StringUtils.containsAny(CharU20001, CharUSuppCharHigh.toCharArray()));
136144 assertEquals(0, CharU20001.indexOf(CharUSuppCharLow));
137 assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow.toCharArray()));
138 }
139
140 /**
141 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
142 */
145 assertTrue(StringUtils.containsAny(CharU20001, CharUSuppCharLow.toCharArray()));
146 }
147
148 /**
149 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
150 */
151 @Test
143152 public void testContainsAny_StringCharArrayWithSupplementaryChars() {
144 assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000.toCharArray()));
145 assertEquals(true, StringUtils.containsAny("a" + CharU20000 + CharU20001, "a".toCharArray()));
146 assertEquals(true, StringUtils.containsAny(CharU20000 + "a" + CharU20001, "a".toCharArray()));
147 assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001 + "a", "a".toCharArray()));
148 assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001.toCharArray()));
149 assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000.toCharArray()));
153 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20000.toCharArray()));
154 assertTrue(StringUtils.containsAny("a" + CharU20000 + CharU20001, "a".toCharArray()));
155 assertTrue(StringUtils.containsAny(CharU20000 + "a" + CharU20001, "a".toCharArray()));
156 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001 + "a", "a".toCharArray()));
157 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20001.toCharArray()));
158 assertTrue(StringUtils.containsAny(CharU20000, CharU20000.toCharArray()));
150159 // Sanity check:
151160 assertEquals(-1, CharU20000.indexOf(CharU20001));
152161 assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0)));
153162 assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1)));
154163 // Test:
155 assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001.toCharArray()));
156 assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000.toCharArray()));
157 }
158
164 assertFalse(StringUtils.containsAny(CharU20000, CharU20001.toCharArray()));
165 assertFalse(StringUtils.containsAny(CharU20001, CharU20000.toCharArray()));
166 }
167
168 @Test
159169 public void testContainsAny_StringString() {
160170 assertFalse(StringUtils.containsAny(null, (String) null));
161171 assertFalse(StringUtils.containsAny(null, ""));
173183 }
174184
175185 /**
176 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
177 */
186 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
187 */
188 @Test
178189 public void testContainsAny_StringWithBadSupplementaryChars() {
179190 // Test edge case: 1/2 of a (broken) supplementary char
180 assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001));
191 assertFalse(StringUtils.containsAny(CharUSuppCharHigh, CharU20001));
181192 assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001));
182 assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001));
183 assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh));
193 assertFalse(StringUtils.containsAny(CharUSuppCharLow, CharU20001));
194 assertFalse(StringUtils.containsAny(CharU20001, CharUSuppCharHigh));
184195 assertEquals(0, CharU20001.indexOf(CharUSuppCharLow));
185 assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow));
186 }
187
188 /**
189 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
190 */
196 assertTrue(StringUtils.containsAny(CharU20001, CharUSuppCharLow));
197 }
198
199 /**
200 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
201 */
202 @Test
191203 public void testContainsAny_StringWithSupplementaryChars() {
192 assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000));
193 assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001));
194 assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000));
204 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20000));
205 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20001));
206 assertTrue(StringUtils.containsAny(CharU20000, CharU20000));
195207 // Sanity check:
196208 assertEquals(-1, CharU20000.indexOf(CharU20001));
197209 assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0)));
198210 assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1)));
199211 // Test:
200 assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001));
201 assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000));
202 }
203
212 assertFalse(StringUtils.containsAny(CharU20000, CharU20001));
213 assertFalse(StringUtils.containsAny(CharU20001, CharU20000));
214 }
215
216 @Test
204217 public void testContainsIgnoreCase_LocaleIndependence() {
205 Locale orig = Locale.getDefault();
206
207 Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() };
208
209 String[][] tdata = {
218 final Locale orig = Locale.getDefault();
219
220 final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() };
221
222 final String[][] tdata = {
210223 { "i", "I" },
211224 { "I", "i" },
212225 { "\u03C2", "\u03C3" },
214227 { "\u03A3", "\u03C3" },
215228 };
216229
217 String[][] fdata = {
230 final String[][] fdata = {
218231 { "\u00DF", "SS" },
219232 };
220233
221234 try {
222 for (Locale locale : locales) {
235 for (final Locale locale : locales) {
223236 Locale.setDefault(locale);
224237 for (int j = 0; j < tdata.length; j++) {
225238 assertTrue(Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1], StringUtils
235248 }
236249 }
237250
251 @Test
238252 public void testContainsIgnoreCase_StringString() {
239253 assertFalse(StringUtils.containsIgnoreCase(null, null));
240254
269283 assertTrue(StringUtils.containsIgnoreCase("xabcz", "ABC"));
270284 }
271285
286 @Test
272287 public void testContainsNone_CharArray() {
273 String str1 = "a";
274 String str2 = "b";
275 String str3 = "ab.";
276 char[] chars1= {'b'};
277 char[] chars2= {'.'};
278 char[] chars3= {'c', 'd'};
279 char[] emptyChars = new char[0];
280 assertEquals(true, StringUtils.containsNone(null, (char[]) null));
281 assertEquals(true, StringUtils.containsNone("", (char[]) null));
282 assertEquals(true, StringUtils.containsNone(null, emptyChars));
283 assertEquals(true, StringUtils.containsNone(str1, emptyChars));
284 assertEquals(true, StringUtils.containsNone("", emptyChars));
285 assertEquals(true, StringUtils.containsNone("", chars1));
286 assertEquals(true, StringUtils.containsNone(str1, chars1));
287 assertEquals(true, StringUtils.containsNone(str1, chars2));
288 assertEquals(true, StringUtils.containsNone(str1, chars3));
289 assertEquals(false, StringUtils.containsNone(str2, chars1));
290 assertEquals(true, StringUtils.containsNone(str2, chars2));
291 assertEquals(true, StringUtils.containsNone(str2, chars3));
292 assertEquals(false, StringUtils.containsNone(str3, chars1));
293 assertEquals(false, StringUtils.containsNone(str3, chars2));
294 assertEquals(true, StringUtils.containsNone(str3, chars3));
295 }
296
297 /**
298 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
299 */
288 final String str1 = "a";
289 final String str2 = "b";
290 final String str3 = "ab.";
291 final char[] chars1= {'b'};
292 final char[] chars2= {'.'};
293 final char[] chars3= {'c', 'd'};
294 final char[] emptyChars = new char[0];
295 assertTrue(StringUtils.containsNone(null, (char[]) null));
296 assertTrue(StringUtils.containsNone("", (char[]) null));
297 assertTrue(StringUtils.containsNone(null, emptyChars));
298 assertTrue(StringUtils.containsNone(str1, emptyChars));
299 assertTrue(StringUtils.containsNone("", emptyChars));
300 assertTrue(StringUtils.containsNone("", chars1));
301 assertTrue(StringUtils.containsNone(str1, chars1));
302 assertTrue(StringUtils.containsNone(str1, chars2));
303 assertTrue(StringUtils.containsNone(str1, chars3));
304 assertFalse(StringUtils.containsNone(str2, chars1));
305 assertTrue(StringUtils.containsNone(str2, chars2));
306 assertTrue(StringUtils.containsNone(str2, chars3));
307 assertFalse(StringUtils.containsNone(str3, chars1));
308 assertFalse(StringUtils.containsNone(str3, chars2));
309 assertTrue(StringUtils.containsNone(str3, chars3));
310 }
311
312 /**
313 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
314 */
315 @Test
300316 public void testContainsNone_CharArrayWithBadSupplementaryChars() {
301317 // Test edge case: 1/2 of a (broken) supplementary char
302 assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001.toCharArray()));
318 assertTrue(StringUtils.containsNone(CharUSuppCharHigh, CharU20001.toCharArray()));
303319 assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001));
304 assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001.toCharArray()));
320 assertTrue(StringUtils.containsNone(CharUSuppCharLow, CharU20001.toCharArray()));
305321 assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh));
306 assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh.toCharArray()));
322 assertTrue(StringUtils.containsNone(CharU20001, CharUSuppCharHigh.toCharArray()));
307323 assertEquals(0, CharU20001.indexOf(CharUSuppCharLow));
308 assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow.toCharArray()));
309 }
310
311 /**
312 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
313 */
324 assertFalse(StringUtils.containsNone(CharU20001, CharUSuppCharLow.toCharArray()));
325 }
326
327 /**
328 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
329 */
330 @Test
314331 public void testContainsNone_CharArrayWithSupplementaryChars() {
315 assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000.toCharArray()));
316 assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001.toCharArray()));
317 assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000.toCharArray()));
332 assertFalse(StringUtils.containsNone(CharU20000 + CharU20001, CharU20000.toCharArray()));
333 assertFalse(StringUtils.containsNone(CharU20000 + CharU20001, CharU20001.toCharArray()));
334 assertFalse(StringUtils.containsNone(CharU20000, CharU20000.toCharArray()));
318335 // Sanity check:
319336 assertEquals(-1, CharU20000.indexOf(CharU20001));
320337 assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0)));
321338 assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1)));
322339 // Test:
323 assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001.toCharArray()));
324 assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000.toCharArray()));
325 }
326
340 assertTrue(StringUtils.containsNone(CharU20000, CharU20001.toCharArray()));
341 assertTrue(StringUtils.containsNone(CharU20001, CharU20000.toCharArray()));
342 }
343
344 @Test
327345 public void testContainsNone_String() {
328 String str1 = "a";
329 String str2 = "b";
330 String str3 = "ab.";
331 String chars1= "b";
332 String chars2= ".";
333 String chars3= "cd";
334 assertEquals(true, StringUtils.containsNone(null, (String) null));
335 assertEquals(true, StringUtils.containsNone("", (String) null));
336 assertEquals(true, StringUtils.containsNone(null, ""));
337 assertEquals(true, StringUtils.containsNone(str1, ""));
338 assertEquals(true, StringUtils.containsNone("", ""));
339 assertEquals(true, StringUtils.containsNone("", chars1));
340 assertEquals(true, StringUtils.containsNone(str1, chars1));
341 assertEquals(true, StringUtils.containsNone(str1, chars2));
342 assertEquals(true, StringUtils.containsNone(str1, chars3));
343 assertEquals(false, StringUtils.containsNone(str2, chars1));
344 assertEquals(true, StringUtils.containsNone(str2, chars2));
345 assertEquals(true, StringUtils.containsNone(str2, chars3));
346 assertEquals(false, StringUtils.containsNone(str3, chars1));
347 assertEquals(false, StringUtils.containsNone(str3, chars2));
348 assertEquals(true, StringUtils.containsNone(str3, chars3));
349 }
350
351 /**
352 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
353 */
346 final String str1 = "a";
347 final String str2 = "b";
348 final String str3 = "ab.";
349 final String chars1= "b";
350 final String chars2= ".";
351 final String chars3= "cd";
352 assertTrue(StringUtils.containsNone(null, (String) null));
353 assertTrue(StringUtils.containsNone("", (String) null));
354 assertTrue(StringUtils.containsNone(null, ""));
355 assertTrue(StringUtils.containsNone(str1, ""));
356 assertTrue(StringUtils.containsNone("", ""));
357 assertTrue(StringUtils.containsNone("", chars1));
358 assertTrue(StringUtils.containsNone(str1, chars1));
359 assertTrue(StringUtils.containsNone(str1, chars2));
360 assertTrue(StringUtils.containsNone(str1, chars3));
361 assertFalse(StringUtils.containsNone(str2, chars1));
362 assertTrue(StringUtils.containsNone(str2, chars2));
363 assertTrue(StringUtils.containsNone(str2, chars3));
364 assertFalse(StringUtils.containsNone(str3, chars1));
365 assertFalse(StringUtils.containsNone(str3, chars2));
366 assertTrue(StringUtils.containsNone(str3, chars3));
367 }
368
369 /**
370 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
371 */
372 @Test
354373 public void testContainsNone_StringWithBadSupplementaryChars() {
355374 // Test edge case: 1/2 of a (broken) supplementary char
356 assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001));
375 assertTrue(StringUtils.containsNone(CharUSuppCharHigh, CharU20001));
357376 assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001));
358 assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001));
377 assertTrue(StringUtils.containsNone(CharUSuppCharLow, CharU20001));
359378 assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh));
360 assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh));
379 assertTrue(StringUtils.containsNone(CharU20001, CharUSuppCharHigh));
361380 assertEquals(0, CharU20001.indexOf(CharUSuppCharLow));
362 assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow));
363 }
364
365 /**
366 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
367 */
381 assertFalse(StringUtils.containsNone(CharU20001, CharUSuppCharLow));
382 }
383
384 /**
385 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
386 */
387 @Test
368388 public void testContainsNone_StringWithSupplementaryChars() {
369 assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000));
370 assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001));
371 assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000));
389 assertFalse(StringUtils.containsNone(CharU20000 + CharU20001, CharU20000));
390 assertFalse(StringUtils.containsNone(CharU20000 + CharU20001, CharU20001));
391 assertFalse(StringUtils.containsNone(CharU20000, CharU20000));
372392 // Sanity check:
373393 assertEquals(-1, CharU20000.indexOf(CharU20001));
374394 assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0)));
375395 assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1)));
376396 // Test:
377 assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001));
378 assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000));
379 }
380
397 assertTrue(StringUtils.containsNone(CharU20000, CharU20001));
398 assertTrue(StringUtils.containsNone(CharU20001, CharU20000));
399 }
400
401 @Test
381402 public void testContainsOnly_CharArray() {
382 String str1 = "a";
383 String str2 = "b";
384 String str3 = "ab";
385 char[] chars1= {'b'};
386 char[] chars2= {'a'};
387 char[] chars3= {'a', 'b'};
388 char[] emptyChars = new char[0];
389 assertEquals(false, StringUtils.containsOnly(null, (char[]) null));
390 assertEquals(false, StringUtils.containsOnly("", (char[]) null));
391 assertEquals(false, StringUtils.containsOnly(null, emptyChars));
392 assertEquals(false, StringUtils.containsOnly(str1, emptyChars));
393 assertEquals(true, StringUtils.containsOnly("", emptyChars));
394 assertEquals(true, StringUtils.containsOnly("", chars1));
395 assertEquals(false, StringUtils.containsOnly(str1, chars1));
396 assertEquals(true, StringUtils.containsOnly(str1, chars2));
397 assertEquals(true, StringUtils.containsOnly(str1, chars3));
398 assertEquals(true, StringUtils.containsOnly(str2, chars1));
399 assertEquals(false, StringUtils.containsOnly(str2, chars2));
400 assertEquals(true, StringUtils.containsOnly(str2, chars3));
401 assertEquals(false, StringUtils.containsOnly(str3, chars1));
402 assertEquals(false, StringUtils.containsOnly(str3, chars2));
403 assertEquals(true, StringUtils.containsOnly(str3, chars3));
404 }
405
403 final String str1 = "a";
404 final String str2 = "b";
405 final String str3 = "ab";
406 final char[] chars1= {'b'};
407 final char[] chars2= {'a'};
408 final char[] chars3= {'a', 'b'};
409 final char[] emptyChars = new char[0];
410 assertFalse(StringUtils.containsOnly(null, (char[]) null));
411 assertFalse(StringUtils.containsOnly("", (char[]) null));
412 assertFalse(StringUtils.containsOnly(null, emptyChars));
413 assertFalse(StringUtils.containsOnly(str1, emptyChars));
414 assertTrue(StringUtils.containsOnly("", emptyChars));
415 assertTrue(StringUtils.containsOnly("", chars1));
416 assertFalse(StringUtils.containsOnly(str1, chars1));
417 assertTrue(StringUtils.containsOnly(str1, chars2));
418 assertTrue(StringUtils.containsOnly(str1, chars3));
419 assertTrue(StringUtils.containsOnly(str2, chars1));
420 assertFalse(StringUtils.containsOnly(str2, chars2));
421 assertTrue(StringUtils.containsOnly(str2, chars3));
422 assertFalse(StringUtils.containsOnly(str3, chars1));
423 assertFalse(StringUtils.containsOnly(str3, chars2));
424 assertTrue(StringUtils.containsOnly(str3, chars3));
425 }
426
427 @Test
406428 public void testContainsOnly_String() {
407 String str1 = "a";
408 String str2 = "b";
409 String str3 = "ab";
410 String chars1= "b";
411 String chars2= "a";
412 String chars3= "ab";
413 assertEquals(false, StringUtils.containsOnly(null, (String) null));
414 assertEquals(false, StringUtils.containsOnly("", (String) null));
415 assertEquals(false, StringUtils.containsOnly(null, ""));
416 assertEquals(false, StringUtils.containsOnly(str1, ""));
417 assertEquals(true, StringUtils.containsOnly("", ""));
418 assertEquals(true, StringUtils.containsOnly("", chars1));
419 assertEquals(false, StringUtils.containsOnly(str1, chars1));
420 assertEquals(true, StringUtils.containsOnly(str1, chars2));
421 assertEquals(true, StringUtils.containsOnly(str1, chars3));
422 assertEquals(true, StringUtils.containsOnly(str2, chars1));
423 assertEquals(false, StringUtils.containsOnly(str2, chars2));
424 assertEquals(true, StringUtils.containsOnly(str2, chars3));
425 assertEquals(false, StringUtils.containsOnly(str3, chars1));
426 assertEquals(false, StringUtils.containsOnly(str3, chars2));
427 assertEquals(true, StringUtils.containsOnly(str3, chars3));
428 }
429
429 final String str1 = "a";
430 final String str2 = "b";
431 final String str3 = "ab";
432 final String chars1= "b";
433 final String chars2= "a";
434 final String chars3= "ab";
435 assertFalse(StringUtils.containsOnly(null, (String) null));
436 assertFalse(StringUtils.containsOnly("", (String) null));
437 assertFalse(StringUtils.containsOnly(null, ""));
438 assertFalse(StringUtils.containsOnly(str1, ""));
439 assertTrue(StringUtils.containsOnly("", ""));
440 assertTrue(StringUtils.containsOnly("", chars1));
441 assertFalse(StringUtils.containsOnly(str1, chars1));
442 assertTrue(StringUtils.containsOnly(str1, chars2));
443 assertTrue(StringUtils.containsOnly(str1, chars3));
444 assertTrue(StringUtils.containsOnly(str2, chars1));
445 assertFalse(StringUtils.containsOnly(str2, chars2));
446 assertTrue(StringUtils.containsOnly(str2, chars3));
447 assertFalse(StringUtils.containsOnly(str3, chars1));
448 assertFalse(StringUtils.containsOnly(str3, chars2));
449 assertTrue(StringUtils.containsOnly(str3, chars3));
450 }
451
452 @Test
430453 public void testContainsWhitespace() {
431454 assertFalse( StringUtils.containsWhitespace("") );
432455 assertTrue( StringUtils.containsWhitespace(" ") );
437460 assertTrue( StringUtils.containsWhitespace("\n") );
438461 }
439462
463 // The purpose of this class is to test StringUtils#equals(CharSequence, CharSequence)
464 // with a CharSequence implementation whose equals(Object) override requires that the
465 // other object be an instance of CustomCharSequence, even though, as char sequences,
466 // `seq` may equal the other object.
467 private static class CustomCharSequence implements CharSequence {
468 private final CharSequence seq;
469
470 public CustomCharSequence(final CharSequence seq) {
471 this.seq = seq;
472 }
473
474 @Override
475 public char charAt(final int index) {
476 return seq.charAt(index);
477 }
478
479 @Override
480 public int length() {
481 return seq.length();
482 }
483
484 @Override
485 public CharSequence subSequence(final int start, final int end) {
486 return new CustomCharSequence(seq.subSequence(start, end));
487 }
488
489 @Override
490 public boolean equals(final Object obj) {
491 if (obj == null || !(obj instanceof CustomCharSequence)) {
492 return false;
493 }
494 final CustomCharSequence other = (CustomCharSequence) obj;
495 return seq.equals(other.seq);
496 }
497
498 @Override
499 public int hashCode() {
500 return seq.hashCode();
501 }
502
503 @Override
504 public String toString() {
505 return seq.toString();
506 }
507 }
508
509 @Test
510 public void testCustomCharSequence() {
511 assertThat(new CustomCharSequence(FOO), IsNot.<CharSequence>not(FOO));
512 assertThat(FOO, IsNot.<CharSequence>not(new CustomCharSequence(FOO)));
513 assertEquals(new CustomCharSequence(FOO), new CustomCharSequence(FOO));
514 }
515
516 @Test
440517 public void testEquals() {
441 assertEquals(true, StringUtils.equals(null, null));
442 assertEquals(true, StringUtils.equals(FOO, FOO));
443 assertEquals(true, StringUtils.equals(FOO, new String(new char[] { 'f', 'o', 'o' })));
444 assertEquals(false, StringUtils.equals(FOO, new String(new char[] { 'f', 'O', 'O' })));
445 assertEquals(false, StringUtils.equals(FOO, BAR));
446 assertEquals(false, StringUtils.equals(FOO, null));
447 assertEquals(false, StringUtils.equals(null, FOO));
448 }
449
518 final CharSequence fooCs = FOO, barCs = BAR, foobarCs = FOOBAR;
519 assertTrue(StringUtils.equals(null, null));
520 assertTrue(StringUtils.equals(fooCs, fooCs));
521 assertTrue(StringUtils.equals(fooCs, new StringBuilder(FOO)));
522 assertTrue(StringUtils.equals(fooCs, new String(new char[] { 'f', 'o', 'o' })));
523 assertTrue(StringUtils.equals(fooCs, new CustomCharSequence(FOO)));
524 assertTrue(StringUtils.equals(new CustomCharSequence(FOO), fooCs));
525 assertFalse(StringUtils.equals(fooCs, new String(new char[] { 'f', 'O', 'O' })));
526 assertFalse(StringUtils.equals(fooCs, barCs));
527 assertFalse(StringUtils.equals(fooCs, null));
528 assertFalse(StringUtils.equals(null, fooCs));
529 assertFalse(StringUtils.equals(fooCs, foobarCs));
530 assertFalse(StringUtils.equals(foobarCs, fooCs));
531 }
532
533 @Test
534 public void testEqualsOnStrings() {
535 assertTrue(StringUtils.equals(null, null));
536 assertTrue(StringUtils.equals(FOO, FOO));
537 assertTrue(StringUtils.equals(FOO, new String(new char[] { 'f', 'o', 'o' })));
538 assertFalse(StringUtils.equals(FOO, new String(new char[] { 'f', 'O', 'O' })));
539 assertFalse(StringUtils.equals(FOO, BAR));
540 assertFalse(StringUtils.equals(FOO, null));
541 assertFalse(StringUtils.equals(null, FOO));
542 assertFalse(StringUtils.equals(FOO, FOOBAR));
543 assertFalse(StringUtils.equals(FOOBAR, FOO));
544 }
545
546 @Test
450547 public void testEqualsIgnoreCase() {
451 assertEquals(true, StringUtils.equalsIgnoreCase(null, null));
452 assertEquals(true, StringUtils.equalsIgnoreCase(FOO, FOO));
453 assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'o', 'o' })));
454 assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'O', 'O' })));
455 assertEquals(false, StringUtils.equalsIgnoreCase(FOO, BAR));
456 assertEquals(false, StringUtils.equalsIgnoreCase(FOO, null));
457 assertEquals(false, StringUtils.equalsIgnoreCase(null, FOO));
548 assertTrue(StringUtils.equalsIgnoreCase(null, null));
549 assertTrue(StringUtils.equalsIgnoreCase(FOO, FOO));
550 assertTrue(StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'o', 'o' })));
551 assertTrue(StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'O', 'O' })));
552 assertFalse(StringUtils.equalsIgnoreCase(FOO, BAR));
553 assertFalse(StringUtils.equalsIgnoreCase(FOO, null));
554 assertFalse(StringUtils.equalsIgnoreCase(null, FOO));
555 assertTrue(StringUtils.equalsIgnoreCase("",""));
556 assertFalse(StringUtils.equalsIgnoreCase("abcd","abcd "));
458557 }
459558
460559 //-----------------------------------------------------------------------
560 @Test
461561 public void testIndexOf_char() {
462562 assertEquals(-1, StringUtils.indexOf(null, ' '));
463563 assertEquals(-1, StringUtils.indexOf("", ' '));
467567 assertEquals(2, StringUtils.indexOf(new StringBuilder("aabaabaa"), 'b'));
468568 }
469569
570 @Test
470571 public void testIndexOf_charInt() {
471572 assertEquals(-1, StringUtils.indexOf(null, ' ', 0));
472573 assertEquals(-1, StringUtils.indexOf(null, ' ', -1));
481582 assertEquals(5, StringUtils.indexOf(new StringBuilder("aabaabaa"), 'b', 3));
482583 }
483584
585 @Test
484586 public void testIndexOf_String() {
485587 assertEquals(-1, StringUtils.indexOf(null, null));
486588 assertEquals(-1, StringUtils.indexOf("", null));
493595 assertEquals(2, StringUtils.indexOf(new StringBuilder("aabaabaa"), "b"));
494596 }
495597
598 @Test
496599 public void testIndexOf_StringInt() {
497600 assertEquals(-1, StringUtils.indexOf(null, null, 0));
498601 assertEquals(-1, StringUtils.indexOf(null, null, -1));
515618 assertEquals(2, StringUtils.indexOf("aabaabaa", "b", -1));
516619 assertEquals(2,StringUtils.indexOf("aabaabaa", "", 2));
517620
621 // Test that startIndex works correctly, i.e. cannot match before startIndex
622 assertEquals(7, StringUtils.indexOf("12345678", "8", 5));
623 assertEquals(7, StringUtils.indexOf("12345678", "8", 6));
624 assertEquals(7, StringUtils.indexOf("12345678", "8", 7)); // 7 is last index
625 assertEquals(-1, StringUtils.indexOf("12345678", "8", 8));
626
518627 assertEquals(5, StringUtils.indexOf(new StringBuilder("aabaabaa"), "b", 3));
519628 }
520629
630 @Test
521631 public void testIndexOfAny_StringCharArray() {
522632 assertEquals(-1, StringUtils.indexOfAny(null, (char[]) null));
523633 assertEquals(-1, StringUtils.indexOfAny(null, new char[0]));
535645 }
536646
537647 /**
538 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
539 */
648 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
649 */
650 @Test
540651 public void testIndexOfAny_StringCharArrayWithSupplementaryChars() {
541652 assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000.toCharArray()));
542653 assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001.toCharArray()));
544655 assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001.toCharArray()));
545656 }
546657
658 @Test
547659 public void testIndexOfAny_StringString() {
548660 assertEquals(-1, StringUtils.indexOfAny(null, (String) null));
549661 assertEquals(-1, StringUtils.indexOfAny(null, ""));
560672 assertEquals(-1, StringUtils.indexOfAny("ab", "z"));
561673 }
562674
675 @Test
563676 public void testIndexOfAny_StringStringArray() {
564677 assertEquals(-1, StringUtils.indexOfAny(null, (String[]) null));
565678 assertEquals(-1, StringUtils.indexOfAny(null, FOOBAR_SUB_ARRAY));
578691 }
579692
580693 /**
581 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
582 */
694 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
695 */
696 @Test
583697 public void testIndexOfAny_StringStringWithSupplementaryChars() {
584698 assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000));
585699 assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001));
587701 assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001));
588702 }
589703
704 @Test
590705 public void testIndexOfAnyBut_StringCharArray() {
591706 assertEquals(-1, StringUtils.indexOfAnyBut(null, (char[]) null));
592707 assertEquals(-1, StringUtils.indexOfAnyBut(null, new char[0]));
605720
606721 }
607722
723 @Test
608724 public void testIndexOfAnyBut_StringCharArrayWithSupplementaryChars() {
609725 assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000.toCharArray()));
610726 assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001.toCharArray()));
612728 assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001.toCharArray()));
613729 }
614730
731 @Test
615732 public void testIndexOfAnyBut_StringString() {
616733 assertEquals(-1, StringUtils.indexOfAnyBut(null, (String) null));
617734 assertEquals(-1, StringUtils.indexOfAnyBut(null, ""));
628745 assertEquals(0, StringUtils.indexOfAnyBut("ab", "z"));
629746 }
630747
748 @Test
631749 public void testIndexOfAnyBut_StringStringWithSupplementaryChars() {
632750 assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000));
633751 assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001));
635753 assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001));
636754 }
637755
756 @Test
638757 public void testIndexOfIgnoreCase_String() {
639758 assertEquals(-1, StringUtils.indexOfIgnoreCase(null, null));
640759 assertEquals(-1, StringUtils.indexOfIgnoreCase(null, ""));
649768 assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", ""));
650769 }
651770
771 @Test
652772 public void testIndexOfIgnoreCase_StringInt() {
653773 assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", -1));
654774 assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0));
666786 assertEquals(-1, StringUtils.indexOfIgnoreCase("aab", "AAB", 1));
667787 }
668788
789 @Test
669790 public void testLastIndexOf_char() {
670791 assertEquals(-1, StringUtils.lastIndexOf(null, ' '));
671792 assertEquals(-1, StringUtils.lastIndexOf("", ' '));
675796 assertEquals(5, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), 'b'));
676797 }
677798
799 @Test
678800 public void testLastIndexOf_charInt() {
679801 assertEquals(-1, StringUtils.lastIndexOf(null, ' ', 0));
680802 assertEquals(-1, StringUtils.lastIndexOf(null, ' ', -1));
690812 assertEquals(2, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), 'b', 2));
691813 }
692814
815 @Test
693816 public void testLastIndexOf_String() {
694817 assertEquals(-1, StringUtils.lastIndexOf(null, null));
695818 assertEquals(-1, StringUtils.lastIndexOf("", null));
703826 assertEquals(4, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), "ab"));
704827 }
705828
829 @Test
706830 public void testLastIndexOf_StringInt() {
707831 assertEquals(-1, StringUtils.lastIndexOf(null, null, 0));
708832 assertEquals(-1, StringUtils.lastIndexOf(null, null, -1));
724848 assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", -1));
725849 assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", 0));
726850 assertEquals(0, StringUtils.lastIndexOf("aabaabaa", "a", 0));
851 assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "a", -1));
852
853 // Test that fromIndex works correctly, i.e. cannot match after fromIndex
854 assertEquals(7, StringUtils.lastIndexOf("12345678", "8", 9));
855 assertEquals(7, StringUtils.lastIndexOf("12345678", "8", 8));
856 assertEquals(7, StringUtils.lastIndexOf("12345678", "8", 7)); // 7 is last index
857 assertEquals(-1, StringUtils.lastIndexOf("12345678", "8", 6));
858
859 assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", 1));
860 assertEquals(2, StringUtils.lastIndexOf("aabaabaa", "b", 2));
861 assertEquals(2, StringUtils.lastIndexOf("aabaabaa", "ba", 2));
862 assertEquals(2, StringUtils.lastIndexOf("aabaabaa", "ba", 3));
727863
728864 assertEquals(2, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), "b", 3));
729865 }
730866
867 @Test
731868 public void testLastIndexOfAny_StringStringArray() {
732869 assertEquals(-1, StringUtils.lastIndexOfAny(null, (CharSequence) null)); // test both types of ...
733870 assertEquals(-1, StringUtils.lastIndexOfAny(null, (CharSequence[]) null)); // ... varargs invocation
749886 assertEquals(-1, StringUtils.lastIndexOfAny(null, new String[] {null}));
750887 }
751888
889 @Test
752890 public void testLastIndexOfIgnoreCase_String() {
753891 assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null));
754892 assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null));
766904 assertEquals(0, StringUtils.lastIndexOfIgnoreCase("aab", "AAB"));
767905 }
768906
907 @Test
769908 public void testLastIndexOfIgnoreCase_StringInt() {
770909 assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, 0));
771910 assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, -1));
790929 assertEquals(1, StringUtils.lastIndexOfIgnoreCase("aab", "AB", 1));
791930 }
792931
932 @Test
793933 public void testLastOrdinalIndexOf() {
794934 assertEquals(-1, StringUtils.lastOrdinalIndexOf(null, "*", 42) );
795935 assertEquals(-1, StringUtils.lastOrdinalIndexOf("*", null, 42) );
804944 assertEquals(8, StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) );
805945 }
806946
947 @Test
807948 public void testOrdinalIndexOf() {
808949 assertEquals(-1, StringUtils.ordinalIndexOf(null, null, Integer.MIN_VALUE));
809950 assertEquals(-1, StringUtils.ordinalIndexOf("", null, Integer.MIN_VALUE));
1515 */
1616 package org.apache.commons.lang3;
1717
18 import junit.framework.TestCase;
18 import static org.junit.Assert.assertFalse;
19 import static org.junit.Assert.assertTrue;
20
21 import org.junit.Test;
1922
2023 /**
2124 * Unit tests {@link org.apache.commons.lang3.StringUtils} - Substring methods
2225 *
23 * @version $Id: StringUtilsIsTest.java 1088899 2011-04-05 05:31:27Z bayard $
26 * @version $Id: StringUtilsIsTest.java 1387424 2012-09-19 01:29:22Z sebb $
2427 */
25 public class StringUtilsIsTest extends TestCase {
26
27 public StringUtilsIsTest(String name) {
28 super(name);
29 }
28 public class StringUtilsIsTest {
3029
3130 //-----------------------------------------------------------------------
3231
32 @Test
3333 public void testIsAlpha() {
34 assertEquals(false, StringUtils.isAlpha(null));
35 assertEquals(false, StringUtils.isAlpha(""));
36 assertEquals(false, StringUtils.isAlpha(" "));
37 assertEquals(true, StringUtils.isAlpha("a"));
38 assertEquals(true, StringUtils.isAlpha("A"));
39 assertEquals(true, StringUtils.isAlpha("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
40 assertEquals(false, StringUtils.isAlpha("ham kso"));
41 assertEquals(false, StringUtils.isAlpha("1"));
42 assertEquals(false, StringUtils.isAlpha("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
43 assertEquals(false, StringUtils.isAlpha("_"));
44 assertEquals(false, StringUtils.isAlpha("hkHKHik*khbkuh"));
34 assertFalse(StringUtils.isAlpha(null));
35 assertFalse(StringUtils.isAlpha(""));
36 assertFalse(StringUtils.isAlpha(" "));
37 assertTrue(StringUtils.isAlpha("a"));
38 assertTrue(StringUtils.isAlpha("A"));
39 assertTrue(StringUtils.isAlpha("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
40 assertFalse(StringUtils.isAlpha("ham kso"));
41 assertFalse(StringUtils.isAlpha("1"));
42 assertFalse(StringUtils.isAlpha("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
43 assertFalse(StringUtils.isAlpha("_"));
44 assertFalse(StringUtils.isAlpha("hkHKHik*khbkuh"));
4545 }
4646
47 @Test
4748 public void testIsAlphanumeric() {
48 assertEquals(false, StringUtils.isAlphanumeric(null));
49 assertEquals(false, StringUtils.isAlphanumeric(""));
50 assertEquals(false, StringUtils.isAlphanumeric(" "));
51 assertEquals(true, StringUtils.isAlphanumeric("a"));
52 assertEquals(true, StringUtils.isAlphanumeric("A"));
53 assertEquals(true, StringUtils.isAlphanumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
54 assertEquals(false, StringUtils.isAlphanumeric("ham kso"));
55 assertEquals(true, StringUtils.isAlphanumeric("1"));
56 assertEquals(true, StringUtils.isAlphanumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
57 assertEquals(false, StringUtils.isAlphanumeric("_"));
58 assertEquals(false, StringUtils.isAlphanumeric("hkHKHik*khbkuh"));
49 assertFalse(StringUtils.isAlphanumeric(null));
50 assertFalse(StringUtils.isAlphanumeric(""));
51 assertFalse(StringUtils.isAlphanumeric(" "));
52 assertTrue(StringUtils.isAlphanumeric("a"));
53 assertTrue(StringUtils.isAlphanumeric("A"));
54 assertTrue(StringUtils.isAlphanumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
55 assertFalse(StringUtils.isAlphanumeric("ham kso"));
56 assertTrue(StringUtils.isAlphanumeric("1"));
57 assertTrue(StringUtils.isAlphanumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
58 assertFalse(StringUtils.isAlphanumeric("_"));
59 assertFalse(StringUtils.isAlphanumeric("hkHKHik*khbkuh"));
5960 }
6061
62 @Test
6163 public void testIsWhitespace() {
62 assertEquals(false, StringUtils.isWhitespace(null));
63 assertEquals(true, StringUtils.isWhitespace(""));
64 assertEquals(true, StringUtils.isWhitespace(" "));
65 assertEquals(true, StringUtils.isWhitespace("\t \n \t"));
66 assertEquals(false, StringUtils.isWhitespace("\t aa\n \t"));
67 assertEquals(true, StringUtils.isWhitespace(" "));
68 assertEquals(false, StringUtils.isWhitespace(" a "));
69 assertEquals(false, StringUtils.isWhitespace("a "));
70 assertEquals(false, StringUtils.isWhitespace(" a"));
71 assertEquals(false, StringUtils.isWhitespace("aba"));
72 assertEquals(true, StringUtils.isWhitespace(StringUtilsTest.WHITESPACE));
73 assertEquals(false, StringUtils.isWhitespace(StringUtilsTest.NON_WHITESPACE));
64 assertFalse(StringUtils.isWhitespace(null));
65 assertTrue(StringUtils.isWhitespace(""));
66 assertTrue(StringUtils.isWhitespace(" "));
67 assertTrue(StringUtils.isWhitespace("\t \n \t"));
68 assertFalse(StringUtils.isWhitespace("\t aa\n \t"));
69 assertTrue(StringUtils.isWhitespace(" "));
70 assertFalse(StringUtils.isWhitespace(" a "));
71 assertFalse(StringUtils.isWhitespace("a "));
72 assertFalse(StringUtils.isWhitespace(" a"));
73 assertFalse(StringUtils.isWhitespace("aba"));
74 assertTrue(StringUtils.isWhitespace(StringUtilsTest.WHITESPACE));
75 assertFalse(StringUtils.isWhitespace(StringUtilsTest.NON_WHITESPACE));
7476 }
7577
78 @Test
7679 public void testIsAlphaspace() {
77 assertEquals(false, StringUtils.isAlphaSpace(null));
78 assertEquals(true, StringUtils.isAlphaSpace(""));
79 assertEquals(true, StringUtils.isAlphaSpace(" "));
80 assertEquals(true, StringUtils.isAlphaSpace("a"));
81 assertEquals(true, StringUtils.isAlphaSpace("A"));
82 assertEquals(true, StringUtils.isAlphaSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
83 assertEquals(true, StringUtils.isAlphaSpace("ham kso"));
84 assertEquals(false, StringUtils.isAlphaSpace("1"));
85 assertEquals(false, StringUtils.isAlphaSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
86 assertEquals(false, StringUtils.isAlphaSpace("_"));
87 assertEquals(false, StringUtils.isAlphaSpace("hkHKHik*khbkuh"));
80 assertFalse(StringUtils.isAlphaSpace(null));
81 assertTrue(StringUtils.isAlphaSpace(""));
82 assertTrue(StringUtils.isAlphaSpace(" "));
83 assertTrue(StringUtils.isAlphaSpace("a"));
84 assertTrue(StringUtils.isAlphaSpace("A"));
85 assertTrue(StringUtils.isAlphaSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
86 assertTrue(StringUtils.isAlphaSpace("ham kso"));
87 assertFalse(StringUtils.isAlphaSpace("1"));
88 assertFalse(StringUtils.isAlphaSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
89 assertFalse(StringUtils.isAlphaSpace("_"));
90 assertFalse(StringUtils.isAlphaSpace("hkHKHik*khbkuh"));
8891 }
8992
93 @Test
9094 public void testIsAlphanumericSpace() {
91 assertEquals(false, StringUtils.isAlphanumericSpace(null));
92 assertEquals(true, StringUtils.isAlphanumericSpace(""));
93 assertEquals(true, StringUtils.isAlphanumericSpace(" "));
94 assertEquals(true, StringUtils.isAlphanumericSpace("a"));
95 assertEquals(true, StringUtils.isAlphanumericSpace("A"));
96 assertEquals(true, StringUtils.isAlphanumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
97 assertEquals(true, StringUtils.isAlphanumericSpace("ham kso"));
98 assertEquals(true, StringUtils.isAlphanumericSpace("1"));
99 assertEquals(true, StringUtils.isAlphanumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
100 assertEquals(false, StringUtils.isAlphanumericSpace("_"));
101 assertEquals(false, StringUtils.isAlphanumericSpace("hkHKHik*khbkuh"));
95 assertFalse(StringUtils.isAlphanumericSpace(null));
96 assertTrue(StringUtils.isAlphanumericSpace(""));
97 assertTrue(StringUtils.isAlphanumericSpace(" "));
98 assertTrue(StringUtils.isAlphanumericSpace("a"));
99 assertTrue(StringUtils.isAlphanumericSpace("A"));
100 assertTrue(StringUtils.isAlphanumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
101 assertTrue(StringUtils.isAlphanumericSpace("ham kso"));
102 assertTrue(StringUtils.isAlphanumericSpace("1"));
103 assertTrue(StringUtils.isAlphanumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
104 assertFalse(StringUtils.isAlphanumericSpace("_"));
105 assertFalse(StringUtils.isAlphanumericSpace("hkHKHik*khbkuh"));
102106 }
103107
108 @Test
104109 public void testIsAsciiPrintable_String() {
105 assertEquals(false, StringUtils.isAsciiPrintable(null));
106 assertEquals(true, StringUtils.isAsciiPrintable(""));
107 assertEquals(true, StringUtils.isAsciiPrintable(" "));
108 assertEquals(true, StringUtils.isAsciiPrintable("a"));
109 assertEquals(true, StringUtils.isAsciiPrintable("A"));
110 assertEquals(true, StringUtils.isAsciiPrintable("1"));
111 assertEquals(true, StringUtils.isAsciiPrintable("Ceki"));
112 assertEquals(true, StringUtils.isAsciiPrintable("!ab2c~"));
113 assertEquals(true, StringUtils.isAsciiPrintable("1000"));
114 assertEquals(true, StringUtils.isAsciiPrintable("10 00"));
115 assertEquals(false, StringUtils.isAsciiPrintable("10\t00"));
116 assertEquals(true, StringUtils.isAsciiPrintable("10.00"));
117 assertEquals(true, StringUtils.isAsciiPrintable("10,00"));
118 assertEquals(true, StringUtils.isAsciiPrintable("!ab-c~"));
119 assertEquals(true, StringUtils.isAsciiPrintable("hkHK=Hik6i?UGH_KJgU7.tUJgKJ*GI87GI,kug"));
120 assertEquals(true, StringUtils.isAsciiPrintable("\u0020"));
121 assertEquals(true, StringUtils.isAsciiPrintable("\u0021"));
122 assertEquals(true, StringUtils.isAsciiPrintable("\u007e"));
123 assertEquals(false, StringUtils.isAsciiPrintable("\u007f"));
124 assertEquals(true, StringUtils.isAsciiPrintable("G?lc?"));
125 assertEquals(true, StringUtils.isAsciiPrintable("=?iso-8859-1?Q?G=FClc=FC?="));
126 assertEquals(false, StringUtils.isAsciiPrintable("G\u00fclc\u00fc"));
110 assertFalse(StringUtils.isAsciiPrintable(null));
111 assertTrue(StringUtils.isAsciiPrintable(""));
112 assertTrue(StringUtils.isAsciiPrintable(" "));
113 assertTrue(StringUtils.isAsciiPrintable("a"));
114 assertTrue(StringUtils.isAsciiPrintable("A"));
115 assertTrue(StringUtils.isAsciiPrintable("1"));
116 assertTrue(StringUtils.isAsciiPrintable("Ceki"));
117 assertTrue(StringUtils.isAsciiPrintable("!ab2c~"));
118 assertTrue(StringUtils.isAsciiPrintable("1000"));
119 assertTrue(StringUtils.isAsciiPrintable("10 00"));
120 assertFalse(StringUtils.isAsciiPrintable("10\t00"));
121 assertTrue(StringUtils.isAsciiPrintable("10.00"));
122 assertTrue(StringUtils.isAsciiPrintable("10,00"));
123 assertTrue(StringUtils.isAsciiPrintable("!ab-c~"));
124 assertTrue(StringUtils.isAsciiPrintable("hkHK=Hik6i?UGH_KJgU7.tUJgKJ*GI87GI,kug"));
125 assertTrue(StringUtils.isAsciiPrintable("\u0020"));
126 assertTrue(StringUtils.isAsciiPrintable("\u0021"));
127 assertTrue(StringUtils.isAsciiPrintable("\u007e"));
128 assertFalse(StringUtils.isAsciiPrintable("\u007f"));
129 assertTrue(StringUtils.isAsciiPrintable("G?lc?"));
130 assertTrue(StringUtils.isAsciiPrintable("=?iso-8859-1?Q?G=FClc=FC?="));
131 assertFalse(StringUtils.isAsciiPrintable("G\u00fclc\u00fc"));
127132 }
128133
134 @Test
129135 public void testIsNumeric() {
130 assertEquals(false, StringUtils.isNumeric(null));
131 assertEquals(false, StringUtils.isNumeric(""));
132 assertEquals(false, StringUtils.isNumeric(" "));
133 assertEquals(false, StringUtils.isNumeric("a"));
134 assertEquals(false, StringUtils.isNumeric("A"));
135 assertEquals(false, StringUtils.isNumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
136 assertEquals(false, StringUtils.isNumeric("ham kso"));
137 assertEquals(true, StringUtils.isNumeric("1"));
138 assertEquals(true, StringUtils.isNumeric("1000"));
139 assertEquals(false, StringUtils.isNumeric("2.3"));
140 assertEquals(false, StringUtils.isNumeric("10 00"));
141 assertEquals(false, StringUtils.isNumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
142 assertEquals(false, StringUtils.isNumeric("_"));
143 assertEquals(false, StringUtils.isNumeric("hkHKHik*khbkuh"));
136 assertFalse(StringUtils.isNumeric(null));
137 assertFalse(StringUtils.isNumeric(""));
138 assertFalse(StringUtils.isNumeric(" "));
139 assertFalse(StringUtils.isNumeric("a"));
140 assertFalse(StringUtils.isNumeric("A"));
141 assertFalse(StringUtils.isNumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
142 assertFalse(StringUtils.isNumeric("ham kso"));
143 assertTrue(StringUtils.isNumeric("1"));
144 assertTrue(StringUtils.isNumeric("1000"));
145 assertFalse(StringUtils.isNumeric("2.3"));
146 assertFalse(StringUtils.isNumeric("10 00"));
147 assertFalse(StringUtils.isNumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
148 assertFalse(StringUtils.isNumeric("_"));
149 assertFalse(StringUtils.isNumeric("hkHKHik*khbkuh"));
150 assertFalse(StringUtils.isNumeric("+123"));
151 assertFalse(StringUtils.isNumeric("-123"));
144152 }
145153
154 @Test
146155 public void testIsNumericSpace() {
147 assertEquals(false, StringUtils.isNumericSpace(null));
148 assertEquals(true, StringUtils.isNumericSpace(""));
149 assertEquals(true, StringUtils.isNumericSpace(" "));
150 assertEquals(false, StringUtils.isNumericSpace("a"));
151 assertEquals(false, StringUtils.isNumericSpace("A"));
152 assertEquals(false, StringUtils.isNumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
153 assertEquals(false, StringUtils.isNumericSpace("ham kso"));
154 assertEquals(true, StringUtils.isNumericSpace("1"));
155 assertEquals(true, StringUtils.isNumericSpace("1000"));
156 assertEquals(false, StringUtils.isNumericSpace("2.3"));
157 assertEquals(true, StringUtils.isNumericSpace("10 00"));
158 assertEquals(false, StringUtils.isNumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
159 assertEquals(false, StringUtils.isNumericSpace("_"));
160 assertEquals(false, StringUtils.isNumericSpace("hkHKHik*khbkuh"));
156 assertFalse(StringUtils.isNumericSpace(null));
157 assertTrue(StringUtils.isNumericSpace(""));
158 assertTrue(StringUtils.isNumericSpace(" "));
159 assertFalse(StringUtils.isNumericSpace("a"));
160 assertFalse(StringUtils.isNumericSpace("A"));
161 assertFalse(StringUtils.isNumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
162 assertFalse(StringUtils.isNumericSpace("ham kso"));
163 assertTrue(StringUtils.isNumericSpace("1"));
164 assertTrue(StringUtils.isNumericSpace("1000"));
165 assertFalse(StringUtils.isNumericSpace("2.3"));
166 assertTrue(StringUtils.isNumericSpace("10 00"));
167 assertFalse(StringUtils.isNumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
168 assertFalse(StringUtils.isNumericSpace("_"));
169 assertFalse(StringUtils.isNumericSpace("hkHKHik*khbkuh"));
161170 }
162171
163172 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import junit.framework.TestCase;
19
18 import org.junit.Test;
19 import static org.junit.Assert.*;
2020 import org.apache.commons.lang3.text.StrBuilder;
2121
2222 /**
2323 * Unit tests {@link org.apache.commons.lang3.StringUtils} - StartsWith/EndsWith methods
2424 *
25 * @version $Id: StringUtilsStartsEndsWithTest.java 1144929 2011-07-10 18:26:16Z ggregory $
25 * @version $Id: StringUtilsStartsEndsWithTest.java 1469220 2013-04-18 08:15:47Z bayard $
2626 */
27 public class StringUtilsStartsEndsWithTest extends TestCase {
27 public class StringUtilsStartsEndsWithTest {
2828 private static final String foo = "foo";
2929 private static final String bar = "bar";
3030 private static final String foobar = "foobar";
3232 private static final String BAR = "BAR";
3333 private static final String FOOBAR = "FOOBAR";
3434
35 public StringUtilsStartsEndsWithTest(String name) {
36 super(name);
37 }
38
3935 //-----------------------------------------------------------------------
4036
4137 /**
4238 * Test StringUtils.startsWith()
4339 */
40 @Test
4441 public void testStartsWith() {
4542 assertTrue("startsWith(null, null)", StringUtils.startsWith(null, (String)null));
4643 assertFalse("startsWith(FOOBAR, null)", StringUtils.startsWith(FOOBAR, (String)null));
6461 /**
6562 * Test StringUtils.testStartsWithIgnoreCase()
6663 */
64 @Test
6765 public void testStartsWithIgnoreCase() {
6866 assertTrue("startsWithIgnoreCase(null, null)", StringUtils.startsWithIgnoreCase(null, (String)null));
6967 assertFalse("startsWithIgnoreCase(FOOBAR, null)", StringUtils.startsWithIgnoreCase(FOOBAR, (String)null));
8482 assertFalse("startsWithIgnoreCase(FOOBAR, bar)", StringUtils.startsWithIgnoreCase(FOOBAR, bar));
8583 }
8684
85 @Test
8786 public void testStartsWithAny() {
8887 assertFalse(StringUtils.startsWithAny(null, (String[])null));
8988 assertFalse(StringUtils.startsWithAny(null, "abc"));
101100 /**
102101 * Test StringUtils.endsWith()
103102 */
103 @Test
104104 public void testEndsWith() {
105105 assertTrue("endsWith(null, null)", StringUtils.endsWith(null, (String)null));
106106 assertFalse("endsWith(FOOBAR, null)", StringUtils.endsWith(FOOBAR, (String)null));
119119 assertTrue("endsWith(FOOBAR, BAR)", StringUtils.endsWith(FOOBAR, BAR));
120120 assertFalse("endsWith(foobar, BAR)", StringUtils.endsWith(foobar, BAR));
121121 assertFalse("endsWith(FOOBAR, bar)", StringUtils.endsWith(FOOBAR, bar));
122
123 // "alpha,beta,gamma,delta".endsWith("delta")
124 assertTrue("endsWith(\u03B1\u03B2\u03B3\u03B4, \u03B4)",
125 StringUtils.endsWith("\u03B1\u03B2\u03B3\u03B4", "\u03B4"));
126 // "alpha,beta,gamma,delta".endsWith("gamma,DELTA")
127 assertFalse("endsWith(\u03B1\u03B2\u03B3\u03B4, \u03B3\u0394)",
128 StringUtils.endsWith("\u03B1\u03B2\u03B3\u03B4", "\u03B3\u0394"));
122129 }
123130
124131 /**
125132 * Test StringUtils.endsWithIgnoreCase()
126133 */
134 @Test
127135 public void testEndsWithIgnoreCase() {
128136 assertTrue("endsWithIgnoreCase(null, null)", StringUtils.endsWithIgnoreCase(null, (String)null));
129137 assertFalse("endsWithIgnoreCase(FOOBAR, null)", StringUtils.endsWithIgnoreCase(FOOBAR, (String)null));
147155 assertTrue(StringUtils.endsWithIgnoreCase("abcdef", "def"));
148156 assertTrue(StringUtils.endsWithIgnoreCase("ABCDEF", "def"));
149157 assertFalse(StringUtils.endsWithIgnoreCase("ABCDEF", "cde"));
158
159 // "alpha,beta,gamma,delta".endsWith("DELTA")
160 assertTrue("endsWith(\u03B1\u03B2\u03B3\u03B4, \u0394)",
161 StringUtils.endsWithIgnoreCase("\u03B1\u03B2\u03B3\u03B4", "\u0394"));
162 // "alpha,beta,gamma,delta".endsWith("GAMMA")
163 assertFalse("endsWith(\u03B1\u03B2\u03B3\u03B4, \u0393)",
164 StringUtils.endsWithIgnoreCase("\u03B1\u03B2\u03B3\u03B4", "\u0393"));
150165 }
151166
167 @Test
152168 public void testEndsWithAny() {
153169 assertFalse("StringUtils.endsWithAny(null, null)", StringUtils.endsWithAny(null, (String)null));
154170 assertFalse("StringUtils.endsWithAny(null, new String[] {abc})", StringUtils.endsWithAny(null, new String[] {"abc"}));
1515 */
1616 package org.apache.commons.lang3;
1717
18 import junit.framework.TestCase;
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertNull;
20 import static org.junit.Assert.assertSame;
21
22 import org.junit.Test;
1923
2024 /**
2125 * Unit tests {@link org.apache.commons.lang3.StringUtils} - Substring methods
2226 *
23 * @version $Id: StringUtilsSubstringTest.java 1089970 2011-04-07 20:05:50Z sebb $
27 * @version $Id: StringUtilsSubstringTest.java 1387361 2012-09-18 21:07:42Z mbenson $
2428 */
25 public class StringUtilsSubstringTest extends TestCase {
29 public class StringUtilsSubstringTest {
2630 private static final String FOO = "foo";
2731 private static final String BAR = "bar";
2832 private static final String BAZ = "baz";
2933 private static final String FOOBAR = "foobar";
3034 private static final String SENTENCE = "foo bar baz";
3135
32 public StringUtilsSubstringTest(String name) {
33 super(name);
34 }
35
3636 //-----------------------------------------------------------------------
3737
38
38 @Test
3939 public void testSubstring_StringInt() {
4040 assertEquals(null, StringUtils.substring(null, 0));
4141 assertEquals("", StringUtils.substring("", 0));
5656 assertEquals("", StringUtils.substring("abc", 4));
5757 }
5858
59 @Test
5960 public void testSubstring_StringIntInt() {
6061 assertEquals(null, StringUtils.substring(null, 0, 0));
6162 assertEquals(null, StringUtils.substring(null, 1, 2));
7374 assertEquals("b",StringUtils.substring("abc", -2, -1));
7475 }
7576
77 @Test
7678 public void testLeft_String() {
7779 assertSame(null, StringUtils.left(null, -1));
7880 assertSame(null, StringUtils.left(null, 0));
8890 assertSame(FOOBAR, StringUtils.left(FOOBAR, 80));
8991 }
9092
93 @Test
9194 public void testRight_String() {
9295 assertSame(null, StringUtils.right(null, -1));
9396 assertSame(null, StringUtils.right(null, 0));
103106 assertSame(FOOBAR, StringUtils.right(FOOBAR, 80));
104107 }
105108
109 @Test
106110 public void testMid_String() {
107111 assertSame(null, StringUtils.mid(null, -1, 0));
108112 assertSame(null, StringUtils.mid(null, 0, -1));
125129 }
126130
127131 //-----------------------------------------------------------------------
132 @Test
128133 public void testSubstringBefore_StringString() {
129134 assertEquals("foo", StringUtils.substringBefore("fooXXbarXXbaz", "XX"));
130135
144149 assertEquals("", StringUtils.substringBefore("abc", ""));
145150 }
146151
152 @Test
147153 public void testSubstringAfter_StringString() {
148154 assertEquals("barXXbaz", StringUtils.substringAfter("fooXXbarXXbaz", "XX"));
149155
163169 assertEquals("", StringUtils.substringAfter("abc", "d"));
164170 }
165171
172 @Test
166173 public void testSubstringBeforeLast_StringString() {
167174 assertEquals("fooXXbar", StringUtils.substringBeforeLast("fooXXbarXXbaz", "XX"));
168175
186193 assertEquals("", StringUtils.substringBeforeLast("a", "a"));
187194 }
188195
196 @Test
189197 public void testSubstringAfterLast_StringString() {
190198 assertEquals("baz", StringUtils.substringAfterLast("fooXXbarXXbaz", "XX"));
191199
207215 }
208216
209217 //-----------------------------------------------------------------------
218 @Test
210219 public void testSubstringBetween_StringString() {
211220 assertEquals(null, StringUtils.substringBetween(null, "tag"));
212221 assertEquals("", StringUtils.substringBetween("", ""));
220229 assertEquals("bar", StringUtils.substringBetween("\nbar\n", "\n"));
221230 }
222231
232 @Test
223233 public void testSubstringBetween_StringStringString() {
224234 assertEquals(null, StringUtils.substringBetween(null, "", ""));
225235 assertEquals(null, StringUtils.substringBetween("", null, ""));
235245 /**
236246 * Tests the substringsBetween method that returns an String Array of substrings.
237247 */
248 @Test
238249 public void testSubstringsBetween_StringStringString() {
239250
240251 String[] results = StringUtils.substringsBetween("[one], [two], [three]", "[", "]");
293304 }
294305
295306 //-----------------------------------------------------------------------
307 @Test
296308 public void testCountMatches_String() {
297309 assertEquals(0, StringUtils.countMatches(null, null));
298310 assertEquals(0, StringUtils.countMatches("blah", null));
2929 import java.lang.reflect.Method;
3030 import java.lang.reflect.Modifier;
3131 import java.nio.CharBuffer;
32 import java.nio.charset.Charset;
3233 import java.util.Arrays;
3334 import java.util.Collections;
3435 import java.util.Iterator;
4041 /**
4142 * Unit tests {@link org.apache.commons.lang3.StringUtils}.
4243 *
43 * @version $Id: StringUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
44 * @version $Id: StringUtilsTest.java 1535515 2013-10-24 19:54:47Z bayard $
4445 */
46 @SuppressWarnings("deprecation") // deliberate use of deprecated code
4547 public class StringUtilsTest {
4648
4749 static final String WHITESPACE;
4850 static final String NON_WHITESPACE;
51 static final String HARD_SPACE;
4952 static final String TRIMMABLE;
5053 static final String NON_TRIMMABLE;
5154 static {
5255 String ws = "";
5356 String nws = "";
57 String hs = String.valueOf(((char) 160));
5458 String tr = "";
5559 String ntr = "";
5660 for (int i = 0; i < Character.MAX_VALUE; i++) {
6872 }
6973 WHITESPACE = ws;
7074 NON_WHITESPACE = nws;
75 HARD_SPACE = hs;
7176 TRIMMABLE = tr;
7277 NON_TRIMMABLE = ntr;
7378 }
7681 private static final String[] EMPTY_ARRAY_LIST = {};
7782 private static final String[] NULL_ARRAY_LIST = {null};
7883 private static final Object[] NULL_TO_STRING_LIST = {
79 new Object(){
80 @Override
81 public String toString() {
82 return null;
83 }
84 }
84 new Object(){
85 @Override
86 public String toString() {
87 return null;
88 }
89 }
8590 };
8691 private static final String[] MIXED_ARRAY_LIST = {null, "", "foo"};
8792 private static final Object[] MIXED_TYPE_LIST = {"foo", Long.valueOf(2L)};
93 private static final long[] LONG_PRIM_LIST = {1, 2};
94 private static final int[] INT_PRIM_LIST = {1, 2};
95 private static final byte[] BYTE_PRIM_LIST = {1, 2};
96 private static final short[] SHORT_PRIM_LIST = {1, 2};
97 private static final char[] CHAR_PRIM_LIST = {'1', '2'};
98 private static final float[] FLOAT_PRIM_LIST = {1, 2};
99 private static final double[] DOUBLE_PRIM_LIST = {1, 2};
88100
89101 private static final String SEPARATOR = ",";
90102 private static final char SEPARATOR_CHAR = ';';
103115 @Test
104116 public void testConstructor() {
105117 assertNotNull(new StringUtils());
106 Constructor<?>[] cons = StringUtils.class.getDeclaredConstructors();
118 final Constructor<?>[] cons = StringUtils.class.getDeclaredConstructors();
107119 assertEquals(1, cons.length);
108120 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
109121 assertTrue(Modifier.isPublic(StringUtils.class.getModifiers()));
110122 assertFalse(Modifier.isFinal(StringUtils.class.getModifiers()));
123 }
124
125 //-----------------------------------------------------------------------
126 @Test
127 public void testisEmpty(){
128 assertTrue(StringUtils.isEmpty(null));
129 assertTrue(StringUtils.isEmpty(""));
130 assertFalse(StringUtils.isEmpty(" "));
131 assertFalse(StringUtils.isEmpty("bob"));
132 assertFalse(StringUtils.isEmpty(" bob "));
133 }
134
135 @Test
136 public void testisNotEmpty(){
137 assertFalse(StringUtils.isNotEmpty(null));
138 assertFalse(StringUtils.isNotEmpty(""));
139 assertTrue(StringUtils.isNotEmpty(" "));
140 assertTrue(StringUtils.isNotEmpty("bob"));
141 assertTrue(StringUtils.isNotEmpty(" bob "));
142 }
143
144 @Test
145 public void testisAnyEmpty(){
146 assertTrue(StringUtils.isAnyEmpty(null));
147 assertTrue(StringUtils.isAnyEmpty(null, "foo"));
148 assertTrue(StringUtils.isAnyEmpty("", "bar"));
149 assertTrue(StringUtils.isAnyEmpty("bob", ""));
150 assertTrue(StringUtils.isAnyEmpty(" bob ", null));
151 assertFalse(StringUtils.isAnyEmpty(" ","bar"));
152 assertFalse(StringUtils.isAnyEmpty("foo","bar"));
153 }
154
155 @Test
156 public void testisNoneEmpty(){
157 assertFalse(StringUtils.isNoneEmpty(null));
158 assertFalse(StringUtils.isNoneEmpty(null, "foo"));
159 assertFalse(StringUtils.isNoneEmpty("", "bar"));
160 assertFalse(StringUtils.isNoneEmpty("bob", ""));
161 assertFalse(StringUtils.isNoneEmpty(" bob ", null));
162 assertTrue(StringUtils.isNoneEmpty(" ", "bar"));
163 assertTrue(StringUtils.isNoneEmpty("foo", "bar"));
164 }
165
166 @Test
167 public void testisBlank(){
168 assertTrue(StringUtils.isBlank(null));
169 assertTrue(StringUtils.isBlank(""));
170 assertTrue(StringUtils.isBlank(" "));
171 assertFalse(StringUtils.isBlank("bob"));
172 assertFalse(StringUtils.isBlank(" bob "));
173 }
174
175 @Test
176 public void testisNotBlank(){
177 assertFalse(StringUtils.isNotBlank(null));
178 assertFalse(StringUtils.isNotBlank(""));
179 assertFalse(StringUtils.isNotBlank(" "));
180 assertTrue(StringUtils.isNotBlank("bob"));
181 assertTrue(StringUtils.isNotBlank(" bob "));
182 }
183
184 @Test
185 public void testisAnyBlank(){
186 assertTrue(StringUtils.isAnyBlank(null));
187 assertTrue(StringUtils.isAnyBlank(null, "foo"));
188 assertTrue(StringUtils.isAnyBlank(null, null));
189 assertTrue(StringUtils.isAnyBlank("", "bar"));
190 assertTrue(StringUtils.isAnyBlank("bob", ""));
191 assertTrue(StringUtils.isAnyBlank(" bob ", null));
192 assertTrue(StringUtils.isAnyBlank(" ","bar"));
193 assertFalse(StringUtils.isAnyBlank("foo","bar"));
194 }
195
196 @Test
197 public void testisNoneBlank(){
198 assertFalse(StringUtils.isNoneBlank(null));
199 assertFalse(StringUtils.isNoneBlank(null, "foo"));
200 assertFalse(StringUtils.isNoneBlank(null, null));
201 assertFalse(StringUtils.isNoneBlank("", "bar"));
202 assertFalse(StringUtils.isNoneBlank("bob", ""));
203 assertFalse(StringUtils.isNoneBlank(" bob ", null));
204 assertFalse(StringUtils.isNoneBlank(" ", "bar"));
205 assertTrue(StringUtils.isNoneBlank("foo", "bar"));
111206 }
112207
113208 //-----------------------------------------------------------------------
121216 assertEquals(null, StringUtils.uncapitalize(null));
122217
123218 assertEquals("capitalize(empty-string) failed",
124 "", StringUtils.capitalize("") );
219 "", StringUtils.capitalize("") );
125220 assertEquals("capitalize(single-char-string) failed",
126221 "X", StringUtils.capitalize("x") );
127
222 assertEquals("capitalize(String) failed",
223 FOO_CAP, StringUtils.capitalize(FOO_CAP) );
224 assertEquals("capitalize(string) failed",
225 FOO_CAP, StringUtils.capitalize(FOO_UNCAP) );
226
128227 assertEquals("uncapitalize(String) failed",
129 FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) );
228 FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) );
229 assertEquals("uncapitalize(string) failed",
230 FOO_UNCAP, StringUtils.uncapitalize(FOO_UNCAP) );
130231 assertEquals("uncapitalize(empty-string) failed",
131 "", StringUtils.uncapitalize("") );
232 "", StringUtils.uncapitalize("") );
132233 assertEquals("uncapitalize(single-char-string) failed",
133234 "x", StringUtils.uncapitalize("X") );
134235
176277 assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123") );
177278 assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123") );
178279
179 String test = "This String contains a TitleCase character: \u01C8";
180 String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
280 final String test = "This String contains a TitleCase character: \u01C8";
281 final String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
181282 assertEquals(expect, WordUtils.swapCase(test));
182283 }
183284
207308 }
208309
209310 @Test
210 public void testJoin_ArrayChar() {
311 public void testJoin_ArrayCharSeparator() {
211312 assertEquals(null, StringUtils.join((Object[]) null, ','));
212313 assertEquals(TEXT_LIST_CHAR, StringUtils.join(ARRAY_LIST, SEPARATOR_CHAR));
213314 assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR_CHAR));
220321 assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 2));
221322 assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, '/', 1, 2));
222323 assertEquals("", StringUtils.join(MIXED_TYPE_LIST, '/', 2, 1));
324 }
325
326 @Test
327 public void testJoin_ArrayOfChars() {
328 assertEquals(null, StringUtils.join((char[]) null, ','));
329 assertEquals("1;2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR));
330 assertEquals("2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
331 }
332
333 @Test
334 public void testJoin_ArrayOfBytes() {
335 assertEquals(null, StringUtils.join((byte[]) null, ','));
336 assertEquals("1;2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR));
337 assertEquals("2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
338 }
339
340 @Test
341 public void testJoin_ArrayOfInts() {
342 assertEquals(null, StringUtils.join((int[]) null, ','));
343 assertEquals("1;2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR));
344 assertEquals("2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
345 }
346
347 @Test
348 public void testJoin_ArrayOfLongs() {
349 assertEquals(null, StringUtils.join((long[]) null, ','));
350 assertEquals("1;2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR));
351 assertEquals("2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
352 }
353
354 @Test
355 public void testJoin_ArrayOfFloats() {
356 assertEquals(null, StringUtils.join((float[]) null, ','));
357 assertEquals("1.0;2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR));
358 assertEquals("2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
359 }
360
361 @Test
362 public void testJoin_ArrayOfDoubles() {
363 assertEquals(null, StringUtils.join((double[]) null, ','));
364 assertEquals("1.0;2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR));
365 assertEquals("2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
366 }
367
368 @Test
369 public void testJoin_ArrayOfShorts() {
370 assertEquals(null, StringUtils.join((short[]) null, ','));
371 assertEquals("1;2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR));
372 assertEquals("2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
223373 }
224374
225375 @Test
366516 }
367517
368518 String[] results;
369 String[] expectedResults = {"ab", "de fg"};
519 final String[] expectedResults = {"ab", "de fg"};
370520 results = StringUtils.split("ab de fg", null, 2);
371521 assertEquals(expectedResults.length, results.length);
372522 for (int i = 0; i < expectedResults.length; i++) {
373523 assertEquals(expectedResults[i], results[i]);
374524 }
375525
376 String[] expectedResults2 = {"ab", "cd:ef"};
526 final String[] expectedResults2 = {"ab", "cd:ef"};
377527 results = StringUtils.split("ab:cd:ef",":", 2);
378528 assertEquals(expectedResults2.length, results.length);
379529 for (int i = 0; i < expectedResults2.length; i++) {
381531 }
382532 }
383533
384 private void innerTestSplit(char separator, String sepStr, char noMatch) {
385 String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
534 private void innerTestSplit(final char separator, final String sepStr, final char noMatch) {
535 final String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
386536 "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
387537
388538 final String str = "a" + separator + "b" + separator + separator + noMatch + "c";
427577
428578 assertEquals( 0, StringUtils.splitByWholeSeparator( "", "." ).length ) ;
429579
430 String stringToSplitOnNulls = "ab de fg" ;
431 String[] splitOnNullExpectedResults = { "ab", "de", "fg" } ;
432
433 String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null ) ;
580 final String stringToSplitOnNulls = "ab de fg" ;
581 final String[] splitOnNullExpectedResults = { "ab", "de", "fg" } ;
582
583 final String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null ) ;
434584 assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
435585 for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
436586 assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
437587 }
438588
439 String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiously" ;
440
441 String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
442 String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy" ) ;
589 final String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiously" ;
590
591 final String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
592 final String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy" ) ;
443593 assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
444594 for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i+= 1 ) {
445595 assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
446596 }
447597
448 String[] splitWithMultipleSeparatorExpectedResults = {"ab", "cd", "ef"};
449 String[] splitWithMultipleSeparator = StringUtils.splitByWholeSeparator("ab:cd::ef", ":");
598 final String[] splitWithMultipleSeparatorExpectedResults = {"ab", "cd", "ef"};
599 final String[] splitWithMultipleSeparator = StringUtils.splitByWholeSeparator("ab:cd::ef", ":");
450600 assertEquals( splitWithMultipleSeparatorExpectedResults.length, splitWithMultipleSeparator.length );
451601 for( int i = 0; i < splitWithMultipleSeparatorExpectedResults.length ; i++ ) {
452602 assertEquals( splitWithMultipleSeparatorExpectedResults[i], splitWithMultipleSeparator[i] ) ;
459609
460610 assertEquals( 0, StringUtils.splitByWholeSeparator( "", ".", 3 ).length ) ;
461611
462 String stringToSplitOnNulls = "ab de fg" ;
463 String[] splitOnNullExpectedResults = { "ab", "de fg" } ;
612 final String stringToSplitOnNulls = "ab de fg" ;
613 final String[] splitOnNullExpectedResults = { "ab", "de fg" } ;
464614 //String[] splitOnNullExpectedResults = { "ab", "de" } ;
465615
466 String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null, 2 ) ;
616 final String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null, 2 ) ;
467617 assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
468618 for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
469619 assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
470620 }
471621
472 String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiouslyaeiouyabstemiously" ;
473
474 String[] splitOnStringExpectedResults = { "abstemiously", "abstemiouslyaeiouyabstemiously" } ;
622 final String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiouslyaeiouyabstemiously" ;
623
624 final String[] splitOnStringExpectedResults = { "abstemiously", "abstemiouslyaeiouyabstemiously" } ;
475625 //String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
476 String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy", 2 ) ;
626 final String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy", 2 ) ;
477627 assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
478628 for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i++ ) {
479629 assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
706856 // Match example in javadoc
707857 {
708858 String[] results;
709 String[] expectedResults = {"a", "", "b", "c"};
859 final String[] expectedResults = {"a", "", "b", "c"};
710860 results = StringUtils.splitPreserveAllTokens("a..b.c",'.');
711861 assertEquals(expectedResults.length, results.length);
712862 for (int i = 0; i < expectedResults.length; i++) {
735885
736886 {
737887 String[] results;
738 String[] expectedResults = {"ab", "de fg"};
888 final String[] expectedResults = {"ab", "de fg"};
739889 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
740890 assertEquals(expectedResults.length, results.length);
741891 for (int i = 0; i < expectedResults.length; i++) {
745895
746896 {
747897 String[] results;
748 String[] expectedResults = {"ab", " de fg"};
898 final String[] expectedResults = {"ab", " de fg"};
749899 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
750900 assertEquals(expectedResults.length, results.length);
751901 for (int i = 0; i < expectedResults.length; i++) {
755905
756906 {
757907 String[] results;
758 String[] expectedResults = {"ab", "::de:fg"};
908 final String[] expectedResults = {"ab", "::de:fg"};
759909 results = StringUtils.splitPreserveAllTokens("ab:::de:fg", ":", 2);
760910 assertEquals(expectedResults.length, results.length);
761911 for (int i = 0; i < expectedResults.length; i++) {
765915
766916 {
767917 String[] results;
768 String[] expectedResults = {"ab", "", " de fg"};
918 final String[] expectedResults = {"ab", "", " de fg"};
769919 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 3);
770920 assertEquals(expectedResults.length, results.length);
771921 for (int i = 0; i < expectedResults.length; i++) {
775925
776926 {
777927 String[] results;
778 String[] expectedResults = {"ab", "", "", "de fg"};
928 final String[] expectedResults = {"ab", "", "", "de fg"};
779929 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 4);
780930 assertEquals(expectedResults.length, results.length);
781931 for (int i = 0; i < expectedResults.length; i++) {
784934 }
785935
786936 {
787 String[] expectedResults = {"ab", "cd:ef"};
937 final String[] expectedResults = {"ab", "cd:ef"};
788938 String[] results;
789939 results = StringUtils.splitPreserveAllTokens("ab:cd:ef",":", 2);
790940 assertEquals(expectedResults.length, results.length);
795945
796946 {
797947 String[] results;
798 String[] expectedResults = {"ab", ":cd:ef"};
948 final String[] expectedResults = {"ab", ":cd:ef"};
799949 results = StringUtils.splitPreserveAllTokens("ab::cd:ef",":", 2);
800950 assertEquals(expectedResults.length, results.length);
801951 for (int i = 0; i < expectedResults.length; i++) {
805955
806956 {
807957 String[] results;
808 String[] expectedResults = {"ab", "", ":cd:ef"};
958 final String[] expectedResults = {"ab", "", ":cd:ef"};
809959 results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 3);
810960 assertEquals(expectedResults.length, results.length);
811961 for (int i = 0; i < expectedResults.length; i++) {
815965
816966 {
817967 String[] results;
818 String[] expectedResults = {"ab", "", "", "cd:ef"};
968 final String[] expectedResults = {"ab", "", "", "cd:ef"};
819969 results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 4);
820970 assertEquals(expectedResults.length, results.length);
821971 for (int i = 0; i < expectedResults.length; i++) {
825975
826976 {
827977 String[] results;
828 String[] expectedResults = {"", "ab", "", "", "cd:ef"};
978 final String[] expectedResults = {"", "ab", "", "", "cd:ef"};
829979 results = StringUtils.splitPreserveAllTokens(":ab:::cd:ef",":", 5);
830980 assertEquals(expectedResults.length, results.length);
831981 for (int i = 0; i < expectedResults.length; i++) {
835985
836986 {
837987 String[] results;
838 String[] expectedResults = {"", "", "ab", "", "", "cd:ef"};
988 final String[] expectedResults = {"", "", "ab", "", "", "cd:ef"};
839989 results = StringUtils.splitPreserveAllTokens("::ab:::cd:ef",":", 6);
840990 assertEquals(expectedResults.length, results.length);
841991 for (int i = 0; i < expectedResults.length; i++) {
845995
846996 }
847997
848 private void innerTestSplitPreserveAllTokens(char separator, String sepStr, char noMatch) {
849 String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
998 private void innerTestSplitPreserveAllTokens(final char separator, final String sepStr, final char noMatch) {
999 final String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
8501000 "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
8511001
8521002 final String str = "a" + separator + "b" + separator + separator + noMatch + "c";
9871137 }
9881138
9891139 @Test
1140 public void testReplacePattern() {
1141 assertEquals("X", StringUtils.replacePattern("<A>\nxy\n</A>", "<A>.*</A>", "X"));
1142 }
1143
1144 @Test
1145 public void testRemovePattern() {
1146 assertEquals("", StringUtils.removePattern("<A>x\\ny</A>", "<A>.*</A>"));
1147 }
1148
1149 @Test
9901150 public void testReplace_StringStringStringInt() {
9911151 assertEquals(null, StringUtils.replace(null, null, null, 2));
9921152 assertEquals(null, StringUtils.replace(null, null, "any", 2));
9981158 assertEquals("", StringUtils.replace("", "any", null, 2));
9991159 assertEquals("", StringUtils.replace("", "any", "any", 2));
10001160
1001 String str = new String(new char[] {'o', 'o', 'f', 'o', 'o'});
1161 final String str = new String(new char[] {'o', 'o', 'f', 'o', 'o'});
10021162 assertSame(str, StringUtils.replace(str, "x", "", -1));
10031163
10041164 assertEquals("f", StringUtils.replace("oofoo", "o", "", -1));
10881248 try {
10891249 StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"});
10901250 fail("Should be a circular reference");
1091 } catch (IllegalStateException e) {}
1251 } catch (final IllegalStateException e) {}
10921252
10931253 //JAVADOC TESTS END
10941254 }
11831343 assertEquals("aaa", StringUtils.repeat("a", 3));
11841344 assertEquals("ababab", StringUtils.repeat("ab", 3));
11851345 assertEquals("abcabcabc", StringUtils.repeat("abc", 3));
1186 String str = StringUtils.repeat("a", 10000); // bigger than pad limit
1346 final String str = StringUtils.repeat("a", 10000); // bigger than pad limit
11871347 assertEquals(10000, str.length());
11881348 assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
11891349 }
12051365 @Test
12061366 public void testChop() {
12071367
1208 String[][] chopCases = {
1368 final String[][] chopCases = {
12091369 { FOO_UNCAP + "\r\n", FOO_UNCAP } ,
12101370 { FOO_UNCAP + "\n" , FOO_UNCAP } ,
12111371 { FOO_UNCAP + "\r", FOO_UNCAP },
12191379 { "", "" },
12201380 { "a", "" },
12211381 };
1222 for (String[] chopCase : chopCases) {
1223 String original = chopCase[0];
1224 String expectedResult = chopCase[1];
1382 for (final String[] chopCase : chopCases) {
1383 final String original = chopCase[0];
1384 final String expectedResult = chopCase[1];
12251385 assertEquals("chop(String) failed",
12261386 expectedResult, StringUtils.chop(original));
12271387 }
12301390 @Test
12311391 public void testChomp() {
12321392
1233 String[][] chompCases = {
1393 final String[][] chompCases = {
12341394 { FOO_UNCAP + "\r\n", FOO_UNCAP },
12351395 { FOO_UNCAP + "\n" , FOO_UNCAP },
12361396 { FOO_UNCAP + "\r", FOO_UNCAP },
12481408 { null, null },
12491409 { FOO_UNCAP + "\n\r", FOO_UNCAP + "\n"}
12501410 };
1251 for (String[] chompCase : chompCases) {
1252 String original = chompCase[0];
1253 String expectedResult = chompCase[1];
1411 for (final String[] chompCase : chompCases) {
1412 final String original = chompCase[0];
1413 final String expectedResult = chompCase[1];
12541414 assertEquals("chomp(String) failed",
12551415 expectedResult, StringUtils.chomp(original));
12561416 }
13031463 assertEquals("abc", StringUtils.rightPad("abc", 2, ' '));
13041464 assertEquals("abc", StringUtils.rightPad("abc", -1, ' '));
13051465 assertEquals("abcxx", StringUtils.rightPad("abc", 5, 'x'));
1306 String str = StringUtils.rightPad("aaa", 10000, 'a'); // bigger than pad length
1466 final String str = StringUtils.rightPad("aaa", 10000, 'a'); // bigger than pad length
13071467 assertEquals(10000, str.length());
13081468 assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
13091469 }
13391499 assertEquals("xxabc", StringUtils.leftPad("abc", 5, 'x'));
13401500 assertEquals("\uffff\uffffabc", StringUtils.leftPad("abc", 5, '\uffff'));
13411501 assertEquals("abc", StringUtils.leftPad("abc", 2, ' '));
1342 String str = StringUtils.leftPad("aaa", 10000, 'a'); // bigger than pad length
1502 final String str = StringUtils.leftPad("aaa", 10000, 'a'); // bigger than pad length
13431503 assertEquals(10000, str.length());
13441504 assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
13451505 }
14841644 assertEquals("abc", StringUtils.defaultIfEmpty("abc", "NULL"));
14851645 assertNull(StringUtils.defaultIfEmpty("", null));
14861646 // Tests compatibility for the API return type
1487 String s = StringUtils.defaultIfEmpty("abc", "NULL");
1647 final String s = StringUtils.defaultIfEmpty("abc", "NULL");
14881648 assertEquals("abc", s);
14891649 }
14901650
14961656 assertEquals("abc", StringUtils.defaultIfBlank("abc", "NULL"));
14971657 assertNull(StringUtils.defaultIfBlank("", null));
14981658 // Tests compatibility for the API return type
1499 String s = StringUtils.defaultIfBlank("abc", "NULL");
1659 final String s = StringUtils.defaultIfBlank("abc", "NULL");
15001660 assertEquals("abc", s);
15011661 }
15021662
15061666 assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL")).toString());
15071667 assertNull(StringUtils.defaultIfEmpty(new StringBuilder(""), null));
15081668 // Tests compatibility for the API return type
1509 StringBuilder s = StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL"));
1669 final StringBuilder s = StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL"));
15101670 assertEquals("abc", s.toString());
15111671 }
15121672
15171677 assertEquals("abc", StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL")).toString());
15181678 assertNull(StringUtils.defaultIfBlank(new StringBuilder(""), null));
15191679 // Tests compatibility for the API return type
1520 StringBuilder s = StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL"));
1680 final StringBuilder s = StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL"));
15211681 assertEquals("abc", s.toString());
15221682 }
15231683
15271687 assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL")).toString());
15281688 assertNull(StringUtils.defaultIfEmpty(new StringBuffer(""), null));
15291689 // Tests compatibility for the API return type
1530 StringBuffer s = StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL"));
1690 final StringBuffer s = StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL"));
15311691 assertEquals("abc", s.toString());
15321692 }
15331693
15381698 assertEquals("abc", StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL")).toString());
15391699 assertNull(StringUtils.defaultIfBlank(new StringBuffer(""), null));
15401700 // Tests compatibility for the API return type
1541 StringBuffer s = StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL"));
1701 final StringBuffer s = StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL"));
15421702 assertEquals("abc", s.toString());
15431703 }
15441704
15481708 assertEquals("abc", StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString());
15491709 assertNull(StringUtils.defaultIfEmpty(CharBuffer.wrap(""), null));
15501710 // Tests compatibility for the API return type
1551 CharBuffer s = StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
1711 final CharBuffer s = StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
15521712 assertEquals("abc", s.toString());
15531713 }
15541714
15591719 assertEquals("abc", StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString());
15601720 assertNull(StringUtils.defaultIfBlank(CharBuffer.wrap(""), null));
15611721 // Tests compatibility for the API return type
1562 CharBuffer s = StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
1722 final CharBuffer s = StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
15631723 assertEquals("abc", s.toString());
15641724 }
15651725
15711731 assertEquals("short", StringUtils.abbreviate("short", 10));
15721732 assertEquals("Now is ...", StringUtils.abbreviate("Now is the time for all good men to come to the aid of their party.", 10));
15731733
1574 String raspberry = "raspberry peach";
1734 final String raspberry = "raspberry peach";
15751735 assertEquals("raspberry p...", StringUtils.abbreviate(raspberry, 14));
15761736 assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 15));
15771737 assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 16));
15831743
15841744 try {
15851745 @SuppressWarnings("unused")
1746 final
15861747 String res = StringUtils.abbreviate("abc", 3);
15871748 fail("StringUtils.abbreviate expecting IllegalArgumentException");
1588 } catch (IllegalArgumentException ex) {
1749 } catch (final IllegalArgumentException ex) {
15891750 // empty
15901751 }
15911752 }
15981759
15991760 try {
16001761 @SuppressWarnings("unused")
1762 final
16011763 String res = StringUtils.abbreviate("abcdefghij", 0, 3);
16021764 fail("StringUtils.abbreviate expecting IllegalArgumentException");
1603 } catch (IllegalArgumentException ex) {
1765 } catch (final IllegalArgumentException ex) {
16041766 // empty
16051767 }
16061768 try {
16071769 @SuppressWarnings("unused")
1770 final
16081771 String res = StringUtils.abbreviate("abcdefghij", 5, 6);
16091772 fail("StringUtils.abbreviate expecting IllegalArgumentException");
1610 } catch (IllegalArgumentException ex) {
1773 } catch (final IllegalArgumentException ex) {
16111774 // empty
16121775 }
16131776
16141777
1615 String raspberry = "raspberry peach";
1778 final String raspberry = "raspberry peach";
16161779 assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, 11, 15));
16171780
16181781 assertEquals(null, StringUtils.abbreviate(null, 7, 14));
16381801 assertAbbreviateWithOffset("...ijklmno", Integer.MAX_VALUE, 10);
16391802 }
16401803
1641 private void assertAbbreviateWithOffset(String expected, int offset, int maxWidth) {
1642 String abcdefghijklmno = "abcdefghijklmno";
1643 String message = "abbreviate(String,int,int) failed";
1644 String actual = StringUtils.abbreviate(abcdefghijklmno, offset, maxWidth);
1804 private void assertAbbreviateWithOffset(final String expected, final int offset, final int maxWidth) {
1805 final String abcdefghijklmno = "abcdefghijklmno";
1806 final String message = "abbreviate(String,int,int) failed";
1807 final String actual = StringUtils.abbreviate(abcdefghijklmno, offset, maxWidth);
16451808 if (offset >= 0 && offset < abcdefghijklmno.length()) {
16461809 assertTrue(message + " -- should contain offset character",
16471810 actual.indexOf((char)('a'+offset)) != -1);
16681831 "end to see if the text is complete.", "...", 50) );
16691832
16701833 // Test a much longer text :)
1671 String longText = "Start text" + StringUtils.repeat("x", 10000) + "Close text";
1834 final String longText = "Start text" + StringUtils.repeat("x", 10000) + "Close text";
16721835 assertEquals(
16731836 "Start text->Close text",
16741837 StringUtils.abbreviateMiddle( longText, "->", 22 ) );
17351898 assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo") );
17361899 try {
17371900 @SuppressWarnings("unused")
1901 final
17381902 int d = StringUtils.getLevenshteinDistance("a", null);
17391903 fail("expecting IllegalArgumentException");
1740 } catch (IllegalArgumentException ex) {
1904 } catch (final IllegalArgumentException ex) {
17411905 // empty
17421906 }
17431907 try {
17441908 @SuppressWarnings("unused")
1909 final
17451910 int d = StringUtils.getLevenshteinDistance(null, "a");
17461911 fail("expecting IllegalArgumentException");
1747 } catch (IllegalArgumentException ex) {
1912 } catch (final IllegalArgumentException ex) {
17481913 // empty
17491914 }
17501915 }
18071972 // exceptions
18081973 try {
18091974 @SuppressWarnings("unused")
1975 final
18101976 int d = StringUtils.getLevenshteinDistance("a", null, 0);
18111977 fail("expecting IllegalArgumentException");
1812 } catch (IllegalArgumentException ex) {
1978 } catch (final IllegalArgumentException ex) {
18131979 // empty
18141980 }
18151981 try {
18161982 @SuppressWarnings("unused")
1983 final
18171984 int d = StringUtils.getLevenshteinDistance(null, "a", 0);
18181985 fail("expecting IllegalArgumentException");
1819 } catch (IllegalArgumentException ex) {
1986 } catch (final IllegalArgumentException ex) {
18201987 // empty
18211988 }
18221989
18231990 try {
18241991 @SuppressWarnings("unused")
1992 final
18251993 int d = StringUtils.getLevenshteinDistance("a", "a", -1);
18261994 fail("expecting IllegalArgumentException");
1827 } catch (IllegalArgumentException ex) {
1995 } catch (final IllegalArgumentException ex) {
18281996 // empty
18291997 }
18301998 }
20372205 assertEquals("", StringUtils.getCommonPrefix("xyz", "abcde"));
20382206 assertEquals("i am a ", StringUtils.getCommonPrefix("i am a machine", "i am a robot"));
20392207 }
2040
2208
20412209 @Test
20422210 public void testNormalizeSpace() {
20432211 assertEquals(null, StringUtils.normalizeSpace(null));
20442212 assertEquals("", StringUtils.normalizeSpace(""));
20452213 assertEquals("", StringUtils.normalizeSpace(" "));
20462214 assertEquals("", StringUtils.normalizeSpace("\t"));
2047 assertEquals("", StringUtils.normalizeSpace("\n"));
2215 assertEquals("", StringUtils.normalizeSpace("\n"));
20482216 assertEquals("", StringUtils.normalizeSpace("\u0009"));
20492217 assertEquals("", StringUtils.normalizeSpace("\u000B"));
20502218 assertEquals("", StringUtils.normalizeSpace("\u000C"));
20572225 assertEquals("a", StringUtils.normalizeSpace(" a "));
20582226 assertEquals("a b c", StringUtils.normalizeSpace(" a b c "));
20592227 assertEquals("a b c", StringUtils.normalizeSpace("a\t\f\r b\u000B c\n"));
2228 assertEquals("a b c", StringUtils.normalizeSpace("a\t\f\r " + HARD_SPACE + HARD_SPACE + "b\u000B c\n"));
20602229 }
20612230
20622231 @Test
20712240 // This test enforces that this is done.
20722241 @Test
20732242 public void testStringUtilsCharSequenceContract() {
2074 Class<StringUtils> c = StringUtils.class;
2075 Method[] methods = c.getMethods();
2076 for (Method m : methods) {
2243 final Class<StringUtils> c = StringUtils.class;
2244 final Method[] methods = c.getMethods();
2245 for (final Method m : methods) {
20772246 if (m.getReturnType() == String.class || m.getReturnType() == String[].class) {
20782247 // Assume this is mutable and ensure the first parameter is not CharSequence.
20792248 // It may be String or it may be something else (String[], Object, Object[]) so
20802249 // don't actively test for that.
2081 Class<?>[] params = m.getParameterTypes();
2250 final Class<?>[] params = m.getParameterTypes();
20822251 if ( params.length > 0 && (params[0] == CharSequence.class || params[0] == CharSequence[].class)) {
20832252 fail("The method " + m + " appears to be mutable in spirit and therefore must not accept a CharSequence");
20842253 }
20852254 } else {
20862255 // Assume this is immutable in spirit and ensure the first parameter is not String.
20872256 // As above, it may be something other than CharSequence.
2088 Class<?>[] params = m.getParameterTypes();
2257 final Class<?>[] params = m.getParameterTypes();
20892258 if ( params.length > 0 && (params[0] == String.class || params[0] == String[].class)) {
20902259 fail("The method " + m + " appears to be immutable in spirit and therefore must not accept a String");
20912260 }
21132282 expectedBytes = expectedString.getBytes(encoding);
21142283 assertEquals(expectedString, StringUtils.toString(expectedBytes, encoding));
21152284 }
2285
2286 @Test
2287 public void testEscapeSurrogatePairs() throws Exception {
2288 assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
2289 // Examples from https://en.wikipedia.org/wiki/UTF-16
2290 assertEquals("\uD800\uDC00", StringEscapeUtils.escapeCsv("\uD800\uDC00"));
2291 assertEquals("\uD834\uDD1E", StringEscapeUtils.escapeCsv("\uD834\uDD1E"));
2292 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeCsv("\uDBFF\uDFFD"));
2293 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeHtml3("\uDBFF\uDFFD"));
2294 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeHtml4("\uDBFF\uDFFD"));
2295 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeXml("\uDBFF\uDFFD"));
2296 }
2297
2298 /**
2299 * Tests LANG-858.
2300 *
2301 * @throws Exception
2302 */
2303 @Test
2304 public void testEscapeSurrogatePairsLang858() throws Exception {
2305 assertEquals("\\uDBFF\\uDFFD", StringEscapeUtils.escapeJava("\uDBFF\uDFFD")); //fail LANG-858
2306 assertEquals("\\uDBFF\\uDFFD", StringEscapeUtils.escapeEcmaScript("\uDBFF\uDFFD")); //fail LANG-858
2307 }
2308
2309 @Test
2310 public void testUnescapeSurrogatePairs() throws Exception {
2311 assertEquals("\uD83D\uDE30", StringEscapeUtils.unescapeCsv("\uD83D\uDE30"));
2312 // Examples from https://en.wikipedia.org/wiki/UTF-16
2313 assertEquals("\uD800\uDC00", StringEscapeUtils.unescapeCsv("\uD800\uDC00"));
2314 assertEquals("\uD834\uDD1E", StringEscapeUtils.unescapeCsv("\uD834\uDD1E"));
2315 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.unescapeCsv("\uDBFF\uDFFD"));
2316 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.unescapeHtml3("\uDBFF\uDFFD"));
2317 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.unescapeHtml4("\uDBFF\uDFFD"));
2318 }
2319
2320 /**
2321 * Tests {@code appendIfMissing}.
2322 */
2323 @Test
2324 public void testAppendIfMissing() {
2325 assertEquals("appendIfMissing(null,null)", null, StringUtils.appendIfMissing(null,null));
2326 assertEquals("appendIfMissing(abc,null)", "abc", StringUtils.appendIfMissing("abc",null));
2327 assertEquals("appendIfMissing(\"\",xyz)", "xyz", StringUtils.appendIfMissing("","xyz"));
2328 assertEquals("appendIfMissing(abc,xyz)", "abcxyz", StringUtils.appendIfMissing("abc","xyz"));
2329 assertEquals("appendIfMissing(abcxyz,xyz)", "abcxyz", StringUtils.appendIfMissing("abcxyz","xyz"));
2330 assertEquals("appendIfMissing(aXYZ,xyz)", "aXYZxyz", StringUtils.appendIfMissing("aXYZ","xyz"));
2331
2332 assertEquals("appendIfMissing(null,null,null)", null, StringUtils.appendIfMissing(null,null,(CharSequence[]) null));
2333 assertEquals("appendIfMissing(abc,null,null)", "abc", StringUtils.appendIfMissing("abc",null,(CharSequence[]) null));
2334 assertEquals("appendIfMissing(\"\",xyz,null))", "xyz", StringUtils.appendIfMissing("","xyz",(CharSequence[]) null));
2335 assertEquals("appendIfMissing(abc,xyz,{null})", "abcxyz", StringUtils.appendIfMissing("abc","xyz",new CharSequence[]{null}));
2336 assertEquals("appendIfMissing(abc,xyz,\"\")", "abc", StringUtils.appendIfMissing("abc","xyz",""));
2337 assertEquals("appendIfMissing(abc,xyz,mno)", "abcxyz", StringUtils.appendIfMissing("abc","xyz","mno"));
2338 assertEquals("appendIfMissing(abcxyz,xyz,mno)", "abcxyz", StringUtils.appendIfMissing("abcxyz","xyz","mno"));
2339 assertEquals("appendIfMissing(abcmno,xyz,mno)", "abcmno", StringUtils.appendIfMissing("abcmno","xyz","mno"));
2340 assertEquals("appendIfMissing(abcXYZ,xyz,mno)", "abcXYZxyz", StringUtils.appendIfMissing("abcXYZ","xyz","mno"));
2341 assertEquals("appendIfMissing(abcMNO,xyz,mno)", "abcMNOxyz", StringUtils.appendIfMissing("abcMNO","xyz","mno"));
2342 }
2343
2344 /**
2345 * Tests {@code appendIfMissingIgnoreCase}.
2346 */
2347 @Test
2348 public void testAppendIfMissingIgnoreCase() {
2349 assertEquals("appendIfMissingIgnoreCase(null,null)", null, StringUtils.appendIfMissingIgnoreCase(null,null));
2350 assertEquals("appendIfMissingIgnoreCase(abc,null)", "abc", StringUtils.appendIfMissingIgnoreCase("abc",null));
2351 assertEquals("appendIfMissingIgnoreCase(\"\",xyz)", "xyz", StringUtils.appendIfMissingIgnoreCase("","xyz"));
2352 assertEquals("appendIfMissingIgnoreCase(abc,xyz)", "abcxyz", StringUtils.appendIfMissingIgnoreCase("abc","xyz"));
2353 assertEquals("appendIfMissingIgnoreCase(abcxyz,xyz)", "abcxyz", StringUtils.appendIfMissingIgnoreCase("abcxyz","xyz"));
2354 assertEquals("appendIfMissingIgnoreCase(abcXYZ,xyz)", "abcXYZ", StringUtils.appendIfMissingIgnoreCase("abcXYZ","xyz"));
2355
2356 assertEquals("appendIfMissingIgnoreCase(null,null,null)", null, StringUtils.appendIfMissingIgnoreCase(null,null,(CharSequence[]) null));
2357 assertEquals("appendIfMissingIgnoreCase(abc,null,null)", "abc", StringUtils.appendIfMissingIgnoreCase("abc",null,(CharSequence[]) null));
2358 assertEquals("appendIfMissingIgnoreCase(\"\",xyz,null)", "xyz", StringUtils.appendIfMissingIgnoreCase("","xyz",(CharSequence[]) null));
2359 assertEquals("appendIfMissingIgnoreCase(abc,xyz,{null})", "abcxyz", StringUtils.appendIfMissingIgnoreCase("abc","xyz",new CharSequence[]{null}));
2360 assertEquals("appendIfMissingIgnoreCase(abc,xyz,\"\")", "abc", StringUtils.appendIfMissingIgnoreCase("abc","xyz",""));
2361 assertEquals("appendIfMissingIgnoreCase(abc,xyz,mno)", "abcxyz", StringUtils.appendIfMissingIgnoreCase("abc","xyz","mno"));
2362 assertEquals("appendIfMissingIgnoreCase(abcxyz,xyz,mno)", "abcxyz", StringUtils.appendIfMissingIgnoreCase("abcxyz","xyz","mno"));
2363 assertEquals("appendIfMissingIgnoreCase(abcmno,xyz,mno)", "abcmno", StringUtils.appendIfMissingIgnoreCase("abcmno","xyz","mno"));
2364 assertEquals("appendIfMissingIgnoreCase(abcXYZ,xyz,mno)", "abcXYZ", StringUtils.appendIfMissingIgnoreCase("abcXYZ","xyz","mno"));
2365 assertEquals("appendIfMissingIgnoreCase(abcMNO,xyz,mno)", "abcMNO", StringUtils.appendIfMissingIgnoreCase("abcMNO","xyz","mno"));
2366 }
2367
2368 /**
2369 * Tests {@code prependIfMissing}.
2370 */
2371 @Test
2372 public void testPrependIfMissing() {
2373 assertEquals("prependIfMissing(null,null)", null, StringUtils.prependIfMissing(null,null));
2374 assertEquals("prependIfMissing(abc,null)", "abc", StringUtils.prependIfMissing("abc",null));
2375 assertEquals("prependIfMissing(\"\",xyz)", "xyz", StringUtils.prependIfMissing("","xyz"));
2376 assertEquals("prependIfMissing(abc,xyz)", "xyzabc", StringUtils.prependIfMissing("abc","xyz"));
2377 assertEquals("prependIfMissing(xyzabc,xyz)", "xyzabc", StringUtils.prependIfMissing("xyzabc","xyz"));
2378 assertEquals("prependIfMissing(XYZabc,xyz)", "xyzXYZabc", StringUtils.prependIfMissing("XYZabc","xyz"));
2379
2380 assertEquals("prependIfMissing(null,null null)", null, StringUtils.prependIfMissing(null,null,(CharSequence[]) null));
2381 assertEquals("prependIfMissing(abc,null,null)", "abc", StringUtils.prependIfMissing("abc",null,(CharSequence[]) null));
2382 assertEquals("prependIfMissing(\"\",xyz,null)", "xyz", StringUtils.prependIfMissing("","xyz",(CharSequence[]) null));
2383 assertEquals("prependIfMissing(abc,xyz,{null})","xyzabc", StringUtils.prependIfMissing("abc","xyz",new CharSequence[]{null}));
2384 assertEquals("prependIfMissing(abc,xyz,\"\")","abc", StringUtils.prependIfMissing("abc","xyz",""));
2385 assertEquals("prependIfMissing(abc,xyz,mno)","xyzabc", StringUtils.prependIfMissing("abc","xyz","mno"));
2386 assertEquals("prependIfMissing(xyzabc,xyz,mno)", "xyzabc", StringUtils.prependIfMissing("xyzabc","xyz","mno"));
2387 assertEquals("prependIfMissing(mnoabc,xyz,mno)", "mnoabc", StringUtils.prependIfMissing("mnoabc","xyz","mno"));
2388 assertEquals("prependIfMissing(XYZabc,xyz,mno)", "xyzXYZabc", StringUtils.prependIfMissing("XYZabc","xyz","mno"));
2389 assertEquals("prependIfMissing(MNOabc,xyz,mno)", "xyzMNOabc", StringUtils.prependIfMissing("MNOabc","xyz","mno"));
2390 }
2391
2392 /**
2393 * Tests {@code prependIfMissingIgnoreCase}.
2394 */
2395 @Test
2396 public void testPrependIfMissingIgnoreCase() {
2397 assertEquals("prependIfMissingIgnoreCase(null,null)", null, StringUtils.prependIfMissingIgnoreCase(null,null));
2398 assertEquals("prependIfMissingIgnoreCase(abc,null)", "abc", StringUtils.prependIfMissingIgnoreCase("abc",null));
2399 assertEquals("prependIfMissingIgnoreCase(\"\",xyz)", "xyz", StringUtils.prependIfMissingIgnoreCase("","xyz"));
2400 assertEquals("prependIfMissingIgnoreCase(abc,xyz)", "xyzabc", StringUtils.prependIfMissingIgnoreCase("abc","xyz"));
2401 assertEquals("prependIfMissingIgnoreCase(xyzabc,xyz)", "xyzabc", StringUtils.prependIfMissingIgnoreCase("xyzabc","xyz"));
2402 assertEquals("prependIfMissingIgnoreCase(XYZabc,xyz)", "XYZabc", StringUtils.prependIfMissingIgnoreCase("XYZabc","xyz"));
2403
2404 assertEquals("prependIfMissingIgnoreCase(null,null null)", null, StringUtils.prependIfMissingIgnoreCase(null,null,(CharSequence[]) null));
2405 assertEquals("prependIfMissingIgnoreCase(abc,null,null)", "abc", StringUtils.prependIfMissingIgnoreCase("abc",null,(CharSequence[]) null));
2406 assertEquals("prependIfMissingIgnoreCase(\"\",xyz,null)", "xyz", StringUtils.prependIfMissingIgnoreCase("","xyz",(CharSequence[]) null));
2407 assertEquals("prependIfMissingIgnoreCase(abc,xyz,{null})","xyzabc", StringUtils.prependIfMissingIgnoreCase("abc","xyz",new CharSequence[]{null}));
2408 assertEquals("prependIfMissingIgnoreCase(abc,xyz,\"\")","abc", StringUtils.prependIfMissingIgnoreCase("abc","xyz",""));
2409 assertEquals("prependIfMissingIgnoreCase(abc,xyz,mno)","xyzabc", StringUtils.prependIfMissingIgnoreCase("abc","xyz","mno"));
2410 assertEquals("prependIfMissingIgnoreCase(xyzabc,xyz,mno)", "xyzabc", StringUtils.prependIfMissingIgnoreCase("xyzabc","xyz","mno"));
2411 assertEquals("prependIfMissingIgnoreCase(mnoabc,xyz,mno)", "mnoabc", StringUtils.prependIfMissingIgnoreCase("mnoabc","xyz","mno"));
2412 assertEquals("prependIfMissingIgnoreCase(XYZabc,xyz,mno)", "XYZabc", StringUtils.prependIfMissingIgnoreCase("XYZabc","xyz","mno"));
2413 assertEquals("prependIfMissingIgnoreCase(MNOabc,xyz,mno)", "MNOabc", StringUtils.prependIfMissingIgnoreCase("MNOabc","xyz","mno"));
2414 }
2415
2416 /**
2417 * Tests {@link StringUtils#toString(byte[], Charset)}
2418 *
2419 * @throws UnsupportedEncodingException
2420 * @see StringUtils#toString(byte[], Charset)
2421 */
2422 @Test
2423 public void testToEncodedString() throws UnsupportedEncodingException {
2424 final String expectedString = "The quick brown fox jumped over the lazy dog.";
2425 String encoding = SystemUtils.FILE_ENCODING;
2426 byte[] expectedBytes = expectedString.getBytes(encoding);
2427 // sanity check start
2428 assertArrayEquals(expectedBytes, expectedString.getBytes());
2429 // sanity check end
2430 assertEquals(expectedString, StringUtils.toEncodedString(expectedBytes, Charset.defaultCharset()));
2431 assertEquals(expectedString, StringUtils.toEncodedString(expectedBytes, Charset.forName(encoding)));
2432 encoding = "UTF-16";
2433 expectedBytes = expectedString.getBytes(encoding);
2434 assertEquals(expectedString, StringUtils.toEncodedString(expectedBytes, Charset.forName(encoding)));
2435 }
21162436 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import junit.framework.TestCase;
18 import static org.junit.Assert.assertArrayEquals;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertNull;
22 import static org.junit.Assert.assertTrue;
23
24 import org.junit.Test;
1925
2026 /**
2127 * Unit tests {@link org.apache.commons.lang3.StringUtils} - Trim/Empty methods
2228 *
23 * @version $Id: StringUtilsTrimEmptyTest.java 1132845 2011-06-07 00:50:50Z sebb $
29 * @version $Id: StringUtilsTrimEmptyTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2430 */
25 public class StringUtilsTrimEmptyTest extends TestCase {
31 public class StringUtilsTrimEmptyTest {
2632 private static final String FOO = "foo";
2733
28 public StringUtilsTrimEmptyTest(String name) {
29 super(name);
30 }
31
3234 //-----------------------------------------------------------------------
35 @Test
3336 public void testIsEmpty() {
34 assertEquals(true, StringUtils.isEmpty(null));
35 assertEquals(true, StringUtils.isEmpty(""));
36 assertEquals(false, StringUtils.isEmpty(" "));
37 assertEquals(false, StringUtils.isEmpty("foo"));
38 assertEquals(false, StringUtils.isEmpty(" foo "));
39 }
40
37 assertTrue(StringUtils.isEmpty(null));
38 assertTrue(StringUtils.isEmpty(""));
39 assertFalse(StringUtils.isEmpty(" "));
40 assertFalse(StringUtils.isEmpty("foo"));
41 assertFalse(StringUtils.isEmpty(" foo "));
42 }
43
44 @Test
4145 public void testIsNotEmpty() {
42 assertEquals(false, StringUtils.isNotEmpty(null));
43 assertEquals(false, StringUtils.isNotEmpty(""));
44 assertEquals(true, StringUtils.isNotEmpty(" "));
45 assertEquals(true, StringUtils.isNotEmpty("foo"));
46 assertEquals(true, StringUtils.isNotEmpty(" foo "));
47 }
48
46 assertFalse(StringUtils.isNotEmpty(null));
47 assertFalse(StringUtils.isNotEmpty(""));
48 assertTrue(StringUtils.isNotEmpty(" "));
49 assertTrue(StringUtils.isNotEmpty("foo"));
50 assertTrue(StringUtils.isNotEmpty(" foo "));
51 }
52
53 @Test
4954 public void testIsBlank() {
50 assertEquals(true, StringUtils.isBlank(null));
51 assertEquals(true, StringUtils.isBlank(""));
52 assertEquals(true, StringUtils.isBlank(StringUtilsTest.WHITESPACE));
53 assertEquals(false, StringUtils.isBlank("foo"));
54 assertEquals(false, StringUtils.isBlank(" foo "));
55 }
56
55 assertTrue(StringUtils.isBlank(null));
56 assertTrue(StringUtils.isBlank(""));
57 assertTrue(StringUtils.isBlank(StringUtilsTest.WHITESPACE));
58 assertFalse(StringUtils.isBlank("foo"));
59 assertFalse(StringUtils.isBlank(" foo "));
60 }
61
62 @Test
5763 public void testIsNotBlank() {
58 assertEquals(false, StringUtils.isNotBlank(null));
59 assertEquals(false, StringUtils.isNotBlank(""));
60 assertEquals(false, StringUtils.isNotBlank(StringUtilsTest.WHITESPACE));
61 assertEquals(true, StringUtils.isNotBlank("foo"));
62 assertEquals(true, StringUtils.isNotBlank(" foo "));
64 assertFalse(StringUtils.isNotBlank(null));
65 assertFalse(StringUtils.isNotBlank(""));
66 assertFalse(StringUtils.isNotBlank(StringUtilsTest.WHITESPACE));
67 assertTrue(StringUtils.isNotBlank("foo"));
68 assertTrue(StringUtils.isNotBlank(" foo "));
6369 }
6470
6571 //-----------------------------------------------------------------------
72 @Test
6673 public void testTrim() {
6774 assertEquals(FOO, StringUtils.trim(FOO + " "));
6875 assertEquals(FOO, StringUtils.trim(" " + FOO + " "));
7582 assertEquals(null, StringUtils.trim(null));
7683 }
7784
85 @Test
7886 public void testTrimToNull() {
7987 assertEquals(FOO, StringUtils.trimToNull(FOO + " "));
8088 assertEquals(FOO, StringUtils.trimToNull(" " + FOO + " "));
8795 assertEquals(null, StringUtils.trimToNull(null));
8896 }
8997
98 @Test
9099 public void testTrimToEmpty() {
91100 assertEquals(FOO, StringUtils.trimToEmpty(FOO + " "));
92101 assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO + " "));
100109 }
101110
102111 //-----------------------------------------------------------------------
112 @Test
103113 public void testStrip_String() {
104114 assertEquals(null, StringUtils.strip(null));
105115 assertEquals("", StringUtils.strip(""));
109119 StringUtils.strip(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
110120 }
111121
122 @Test
112123 public void testStripToNull_String() {
113124 assertEquals(null, StringUtils.stripToNull(null));
114125 assertEquals(null, StringUtils.stripToNull(""));
119130 StringUtils.stripToNull(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
120131 }
121132
133 @Test
122134 public void testStripToEmpty_String() {
123135 assertEquals("", StringUtils.stripToEmpty(null));
124136 assertEquals("", StringUtils.stripToEmpty(""));
129141 StringUtils.stripToEmpty(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
130142 }
131143
144 @Test
132145 public void testStrip_StringString() {
133146 // null strip
134147 assertEquals(null, StringUtils.strip(null, null));
160173 assertEquals(StringUtilsTest.WHITESPACE, StringUtils.strip(StringUtilsTest.WHITESPACE, ""));
161174 }
162175
176 @Test
163177 public void testStripStart_StringString() {
164178 // null stripStart
165179 assertEquals(null, StringUtils.stripStart(null, null));
191205 assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE, ""));
192206 }
193207
208 @Test
194209 public void testStripEnd_StringString() {
195210 // null stripEnd
196211 assertEquals(null, StringUtils.stripEnd(null, null));
222237 assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripEnd(StringUtilsTest.WHITESPACE, ""));
223238 }
224239
240 @Test
225241 public void testStripAll() {
226242 // test stripAll method, merely an array version of the above strip
227 String[] empty = new String[0];
228 String[] fooSpace = new String[] { " "+FOO+" ", " "+FOO, FOO+" " };
229 String[] fooDots = new String[] { ".."+FOO+"..", ".."+FOO, FOO+".." };
230 String[] foo = new String[] { FOO, FOO, FOO };
231
232 // assertEquals(null, StringUtils.stripAll(null)); // generates warning
233 assertEquals(null, StringUtils.stripAll((String[]) null)); // equivalent explicit cast
243 final String[] empty = new String[0];
244 final String[] fooSpace = new String[] { " "+FOO+" ", " "+FOO, FOO+" " };
245 final String[] fooDots = new String[] { ".."+FOO+"..", ".."+FOO, FOO+".." };
246 final String[] foo = new String[] { FOO, FOO, FOO };
247
248 assertNull(StringUtils.stripAll((String[]) null));
234249 // Additional varargs tests
235250 assertArrayEquals(empty, StringUtils.stripAll()); // empty array
236251 assertArrayEquals(new String[]{null}, StringUtils.stripAll((String) null)); // == new String[]{null}
238253 assertArrayEquals(empty, StringUtils.stripAll(empty));
239254 assertArrayEquals(foo, StringUtils.stripAll(fooSpace));
240255
241 assertEquals(null, StringUtils.stripAll(null, null));
256 assertNull(StringUtils.stripAll(null, null));
242257 assertArrayEquals(foo, StringUtils.stripAll(fooSpace, null));
243258 assertArrayEquals(foo, StringUtils.stripAll(fooDots, "."));
244259 }
245260
261 @Test
246262 public void testStripAccents() {
247 String cue = "\u00C7\u00FA\u00EA";
263 final String cue = "\u00C7\u00FA\u00EA";
248264 assertEquals( "Failed to strip accents from " + cue, "Cue", StringUtils.stripAccents(cue));
249265
250 String lots = "\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C7\u00C8\u00C9" +
266 final String lots = "\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C7\u00C8\u00C9" +
251267 "\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D1\u00D2\u00D3" +
252268 "\u00D4\u00D5\u00D6\u00D9\u00DA\u00DB\u00DC\u00DD";
253269 assertEquals( "Failed to strip accents from " + lots,
259275 assertEquals( "Failed to handle non-accented text", "control", StringUtils.stripAccents("control") );
260276 assertEquals( "Failed to handle easy example", "eclair", StringUtils.stripAccents("\u00E9clair") );
261277 }
262
263 //-----------------------------------------------------------------------
264
265 private void assertArrayEquals(Object[] o1, Object[] o2) {
266 if(o1 == null) {
267 assertEquals(o1,o2);
268 return;
269 }
270 assertEquals("Length not equal. ", o1.length, o2.length);
271 int sz = o1.length;
272 for(int i=0; i<sz; i++) {
273 if(o1[i] instanceof Object[]) {
274 // do an assert equals on type....
275 assertArrayEquals( (Object[]) o1[i], (Object[]) o2[i] );
276 } else {
277 assertEquals(o1[i], o2[i]);
278 }
279 }
280 }
281
282278 }
1818
1919 package org.apache.commons.lang3;
2020
21 import org.junit.Test;
22 import static org.junit.Assert.*;
2123 import static org.apache.commons.lang3.JavaVersion.JAVA_1_4;
2224
2325 import java.io.File;
2527 import java.lang.reflect.Modifier;
2628 import java.util.Locale;
2729
28 import junit.framework.Assert;
29 import junit.framework.TestCase;
30 import org.junit.Assert;
3031
3132 /**
3233 * Unit tests {@link org.apache.commons.lang3.SystemUtils}.
3334 *
3435 * Only limited testing can be performed.
3536 *
36 * @version $Id: SystemUtilsTest.java 1144929 2011-07-10 18:26:16Z ggregory $
37 * @version $Id: SystemUtilsTest.java 1437526 2013-01-23 16:05:20Z ggregory $
3738 */
38 public class SystemUtilsTest extends TestCase {
39
40 public SystemUtilsTest(String name) {
41 super(name);
42 }
43
39 public class SystemUtilsTest {
40
41 @Test
4442 public void testConstructor() {
4543 assertNotNull(new SystemUtils());
46 Constructor<?>[] cons = SystemUtils.class.getDeclaredConstructors();
44 final Constructor<?>[] cons = SystemUtils.class.getDeclaredConstructors();
4745 assertEquals(1, cons.length);
48 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
49 assertEquals(true, Modifier.isPublic(SystemUtils.class.getModifiers()));
50 assertEquals(false, Modifier.isFinal(SystemUtils.class.getModifiers()));
46 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
47 assertTrue(Modifier.isPublic(SystemUtils.class.getModifiers()));
48 assertFalse(Modifier.isFinal(SystemUtils.class.getModifiers()));
5149 }
5250
5351 /**
5452 * Assums no security manager exists.
5553 */
54 @Test
5655 public void testGetJavaHome() {
57 File dir = SystemUtils.getJavaHome();
56 final File dir = SystemUtils.getJavaHome();
5857 Assert.assertNotNull(dir);
5958 Assert.assertTrue(dir.exists());
6059 }
6261 /**
6362 * Assums no security manager exists.
6463 */
64 @Test
6565 public void testGetJavaIoTmpDir() {
66 File dir = SystemUtils.getJavaIoTmpDir();
66 final File dir = SystemUtils.getJavaIoTmpDir();
6767 Assert.assertNotNull(dir);
6868 Assert.assertTrue(dir.exists());
6969 }
7171 /**
7272 * Assums no security manager exists.
7373 */
74 @Test
7475 public void testGetUserDir() {
75 File dir = SystemUtils.getUserDir();
76 final File dir = SystemUtils.getUserDir();
7677 Assert.assertNotNull(dir);
7778 Assert.assertTrue(dir.exists());
7879 }
8081 /**
8182 * Assums no security manager exists.
8283 */
84 @Test
8385 public void testGetUserHome() {
84 File dir = SystemUtils.getUserHome();
86 final File dir = SystemUtils.getUserHome();
8587 Assert.assertNotNull(dir);
8688 Assert.assertTrue(dir.exists());
8789 }
8890
91 @Test
8992 public void testIS_JAVA() {
90 String javaVersion = System.getProperty("java.version");
93 final String javaVersion = System.getProperty("java.version");
9194 if (javaVersion == null) {
92 assertEquals(false, SystemUtils.IS_JAVA_1_1);
93 assertEquals(false, SystemUtils.IS_JAVA_1_2);
94 assertEquals(false, SystemUtils.IS_JAVA_1_3);
95 assertEquals(false, SystemUtils.IS_JAVA_1_4);
96 assertEquals(false, SystemUtils.IS_JAVA_1_5);
97 assertEquals(false, SystemUtils.IS_JAVA_1_6);
98 assertEquals(false, SystemUtils.IS_JAVA_1_7);
95 assertFalse(SystemUtils.IS_JAVA_1_1);
96 assertFalse(SystemUtils.IS_JAVA_1_2);
97 assertFalse(SystemUtils.IS_JAVA_1_3);
98 assertFalse(SystemUtils.IS_JAVA_1_4);
99 assertFalse(SystemUtils.IS_JAVA_1_5);
100 assertFalse(SystemUtils.IS_JAVA_1_6);
101 assertFalse(SystemUtils.IS_JAVA_1_7);
99102 } else if (javaVersion.startsWith("1.1")) {
100 assertEquals(true, SystemUtils.IS_JAVA_1_1);
101 assertEquals(false, SystemUtils.IS_JAVA_1_2);
102 assertEquals(false, SystemUtils.IS_JAVA_1_3);
103 assertEquals(false, SystemUtils.IS_JAVA_1_4);
104 assertEquals(false, SystemUtils.IS_JAVA_1_5);
105 assertEquals(false, SystemUtils.IS_JAVA_1_6);
106 assertEquals(false, SystemUtils.IS_JAVA_1_7);
103 assertTrue(SystemUtils.IS_JAVA_1_1);
104 assertFalse(SystemUtils.IS_JAVA_1_2);
105 assertFalse(SystemUtils.IS_JAVA_1_3);
106 assertFalse(SystemUtils.IS_JAVA_1_4);
107 assertFalse(SystemUtils.IS_JAVA_1_5);
108 assertFalse(SystemUtils.IS_JAVA_1_6);
109 assertFalse(SystemUtils.IS_JAVA_1_7);
107110 } else if (javaVersion.startsWith("1.2")) {
108 assertEquals(false, SystemUtils.IS_JAVA_1_1);
109 assertEquals(true, SystemUtils.IS_JAVA_1_2);
110 assertEquals(false, SystemUtils.IS_JAVA_1_3);
111 assertEquals(false, SystemUtils.IS_JAVA_1_4);
112 assertEquals(false, SystemUtils.IS_JAVA_1_5);
113 assertEquals(false, SystemUtils.IS_JAVA_1_6);
114 assertEquals(false, SystemUtils.IS_JAVA_1_7);
111 assertFalse(SystemUtils.IS_JAVA_1_1);
112 assertTrue(SystemUtils.IS_JAVA_1_2);
113 assertFalse(SystemUtils.IS_JAVA_1_3);
114 assertFalse(SystemUtils.IS_JAVA_1_4);
115 assertFalse(SystemUtils.IS_JAVA_1_5);
116 assertFalse(SystemUtils.IS_JAVA_1_6);
117 assertFalse(SystemUtils.IS_JAVA_1_7);
115118 } else if (javaVersion.startsWith("1.3")) {
116 assertEquals(false, SystemUtils.IS_JAVA_1_1);
117 assertEquals(false, SystemUtils.IS_JAVA_1_2);
118 assertEquals(true, SystemUtils.IS_JAVA_1_3);
119 assertEquals(false, SystemUtils.IS_JAVA_1_4);
120 assertEquals(false, SystemUtils.IS_JAVA_1_5);
121 assertEquals(false, SystemUtils.IS_JAVA_1_6);
122 assertEquals(false, SystemUtils.IS_JAVA_1_7);
119 assertFalse(SystemUtils.IS_JAVA_1_1);
120 assertFalse(SystemUtils.IS_JAVA_1_2);
121 assertTrue(SystemUtils.IS_JAVA_1_3);
122 assertFalse(SystemUtils.IS_JAVA_1_4);
123 assertFalse(SystemUtils.IS_JAVA_1_5);
124 assertFalse(SystemUtils.IS_JAVA_1_6);
125 assertFalse(SystemUtils.IS_JAVA_1_7);
123126 } else if (javaVersion.startsWith("1.4")) {
124 assertEquals(false, SystemUtils.IS_JAVA_1_1);
125 assertEquals(false, SystemUtils.IS_JAVA_1_2);
126 assertEquals(false, SystemUtils.IS_JAVA_1_3);
127 assertEquals(true, SystemUtils.IS_JAVA_1_4);
128 assertEquals(false, SystemUtils.IS_JAVA_1_5);
129 assertEquals(false, SystemUtils.IS_JAVA_1_6);
130 assertEquals(false, SystemUtils.IS_JAVA_1_7);
127 assertFalse(SystemUtils.IS_JAVA_1_1);
128 assertFalse(SystemUtils.IS_JAVA_1_2);
129 assertFalse(SystemUtils.IS_JAVA_1_3);
130 assertTrue(SystemUtils.IS_JAVA_1_4);
131 assertFalse(SystemUtils.IS_JAVA_1_5);
132 assertFalse(SystemUtils.IS_JAVA_1_6);
133 assertFalse(SystemUtils.IS_JAVA_1_7);
131134 } else if (javaVersion.startsWith("1.5")) {
132 assertEquals(false, SystemUtils.IS_JAVA_1_1);
133 assertEquals(false, SystemUtils.IS_JAVA_1_2);
134 assertEquals(false, SystemUtils.IS_JAVA_1_3);
135 assertEquals(false, SystemUtils.IS_JAVA_1_4);
136 assertEquals(true, SystemUtils.IS_JAVA_1_5);
137 assertEquals(false, SystemUtils.IS_JAVA_1_6);
138 assertEquals(false, SystemUtils.IS_JAVA_1_7);
135 assertFalse(SystemUtils.IS_JAVA_1_1);
136 assertFalse(SystemUtils.IS_JAVA_1_2);
137 assertFalse(SystemUtils.IS_JAVA_1_3);
138 assertFalse(SystemUtils.IS_JAVA_1_4);
139 assertTrue(SystemUtils.IS_JAVA_1_5);
140 assertFalse(SystemUtils.IS_JAVA_1_6);
141 assertFalse(SystemUtils.IS_JAVA_1_7);
139142 } else if (javaVersion.startsWith("1.6")) {
140 assertEquals(false, SystemUtils.IS_JAVA_1_1);
141 assertEquals(false, SystemUtils.IS_JAVA_1_2);
142 assertEquals(false, SystemUtils.IS_JAVA_1_3);
143 assertEquals(false, SystemUtils.IS_JAVA_1_4);
144 assertEquals(false, SystemUtils.IS_JAVA_1_5);
145 assertEquals(true, SystemUtils.IS_JAVA_1_6);
146 assertEquals(false, SystemUtils.IS_JAVA_1_7);
143 assertFalse(SystemUtils.IS_JAVA_1_1);
144 assertFalse(SystemUtils.IS_JAVA_1_2);
145 assertFalse(SystemUtils.IS_JAVA_1_3);
146 assertFalse(SystemUtils.IS_JAVA_1_4);
147 assertFalse(SystemUtils.IS_JAVA_1_5);
148 assertTrue(SystemUtils.IS_JAVA_1_6);
149 assertFalse(SystemUtils.IS_JAVA_1_7);
147150 } else {
148 System.out.println("Can't test IS_JAVA value");
151 System.out.println("Can't test IS_JAVA value: "+javaVersion);
149152 }
150153 }
151154
155 @Test
152156 public void testIS_OS() {
153 String osName = System.getProperty("os.name");
157 final String osName = System.getProperty("os.name");
154158 if (osName == null) {
155 assertEquals(false, SystemUtils.IS_OS_WINDOWS);
156 assertEquals(false, SystemUtils.IS_OS_UNIX);
157 assertEquals(false, SystemUtils.IS_OS_SOLARIS);
158 assertEquals(false, SystemUtils.IS_OS_LINUX);
159 assertEquals(false, SystemUtils.IS_OS_MAC_OSX);
159 assertFalse(SystemUtils.IS_OS_WINDOWS);
160 assertFalse(SystemUtils.IS_OS_UNIX);
161 assertFalse(SystemUtils.IS_OS_SOLARIS);
162 assertFalse(SystemUtils.IS_OS_LINUX);
163 assertFalse(SystemUtils.IS_OS_MAC_OSX);
160164 } else if (osName.startsWith("Windows")) {
161 assertEquals(false, SystemUtils.IS_OS_UNIX);
162 assertEquals(true, SystemUtils.IS_OS_WINDOWS);
165 assertFalse(SystemUtils.IS_OS_UNIX);
166 assertTrue(SystemUtils.IS_OS_WINDOWS);
163167 } else if (osName.startsWith("Solaris")) {
164 assertEquals(true, SystemUtils.IS_OS_SOLARIS);
165 assertEquals(true, SystemUtils.IS_OS_UNIX);
166 assertEquals(false, SystemUtils.IS_OS_WINDOWS);
168 assertTrue(SystemUtils.IS_OS_SOLARIS);
169 assertTrue(SystemUtils.IS_OS_UNIX);
170 assertFalse(SystemUtils.IS_OS_WINDOWS);
167171 } else if (osName.toLowerCase(Locale.ENGLISH).startsWith("linux")) {
168 assertEquals(true, SystemUtils.IS_OS_LINUX);
169 assertEquals(true, SystemUtils.IS_OS_UNIX);
170 assertEquals(false, SystemUtils.IS_OS_WINDOWS);
172 assertTrue(SystemUtils.IS_OS_LINUX);
173 assertTrue(SystemUtils.IS_OS_UNIX);
174 assertFalse(SystemUtils.IS_OS_WINDOWS);
171175 } else if (osName.startsWith("Mac OS X")) {
172 assertEquals(true, SystemUtils.IS_OS_MAC_OSX);
173 assertEquals(true, SystemUtils.IS_OS_UNIX);
174 assertEquals(false, SystemUtils.IS_OS_WINDOWS);
176 assertTrue(SystemUtils.IS_OS_MAC_OSX);
177 assertTrue(SystemUtils.IS_OS_UNIX);
178 assertFalse(SystemUtils.IS_OS_WINDOWS);
175179 } else if (osName.startsWith("OS/2")) {
176 assertEquals(true, SystemUtils.IS_OS_OS2);
177 assertEquals(false, SystemUtils.IS_OS_UNIX);
178 assertEquals(false, SystemUtils.IS_OS_WINDOWS);
180 assertTrue(SystemUtils.IS_OS_OS2);
181 assertFalse(SystemUtils.IS_OS_UNIX);
182 assertFalse(SystemUtils.IS_OS_WINDOWS);
179183 } else if (osName.startsWith("SunOS")) {
180 assertEquals(true, SystemUtils.IS_OS_SUN_OS);
181 assertEquals(true, SystemUtils.IS_OS_UNIX);
182 assertEquals(false, SystemUtils.IS_OS_WINDOWS);
184 assertTrue(SystemUtils.IS_OS_SUN_OS);
185 assertTrue(SystemUtils.IS_OS_UNIX);
186 assertFalse(SystemUtils.IS_OS_WINDOWS);
187 } else if (osName.startsWith("FreeBSD")) {
188 assertTrue(SystemUtils.IS_OS_FREE_BSD);
189 assertTrue(SystemUtils.IS_OS_UNIX);
190 assertFalse(SystemUtils.IS_OS_WINDOWS);
183191 } else {
184 System.out.println("Can't test IS_OS value");
192 System.out.println("Can't test IS_OS value: "+osName);
185193 }
186194 }
187195
196 @Test
188197 public void testJavaVersionMatches() {
189198 String javaVersion = null;
190 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
191 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
192 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
193 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
194 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
195 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
196 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
197 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
199 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
200 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
201 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
202 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
203 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
204 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
205 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
206 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
198207 javaVersion = "";
199 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
200 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
201 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
202 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
203 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
204 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
205 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
206 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
208 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
209 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
210 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
211 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
212 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
213 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
214 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
215 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
207216 javaVersion = "1.0";
208 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
209 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
210 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
211 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
212 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
213 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
214 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
215 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
217 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
218 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
219 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
220 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
221 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
222 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
223 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
224 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
216225 javaVersion = "1.1";
217 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
218 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
219 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
220 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
221 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
222 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
223 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
224 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
226 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
227 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
228 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
229 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
230 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
231 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
232 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
233 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
225234 javaVersion = "1.2";
226 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
227 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
228 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
229 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
230 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
231 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
232 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
233 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
235 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
236 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
237 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
238 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
239 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
240 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
241 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
242 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
234243 javaVersion = "1.3.0";
235 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
236 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
237 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
238 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
239 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
240 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
241 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
242 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
244 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
245 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
246 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
247 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
248 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
249 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
250 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
251 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
243252 javaVersion = "1.3.1";
244 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
245 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
246 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
247 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
248 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
249 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
250 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
251 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
253 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
254 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
255 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
256 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
257 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
258 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
259 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
260 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
252261 javaVersion = "1.4.0";
253 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
254 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
255 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
256 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
257 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
258 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
259 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
260 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
262 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
263 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
264 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
265 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
266 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
267 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
268 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
269 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
261270 javaVersion = "1.4.1";
262 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
263 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
264 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
265 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
266 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
267 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
268 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
269 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
271 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
272 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
273 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
274 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
275 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
276 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
277 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
278 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
270279 javaVersion = "1.4.2";
271 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
272 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
273 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
274 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
275 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
276 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
277 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
278 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
280 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
281 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
282 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
283 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
284 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
285 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
286 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
287 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
279288 javaVersion = "1.5.0";
280 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
281 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
282 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
283 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
284 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
285 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
286 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
287 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
289 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
290 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
291 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
292 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
293 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
294 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
295 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
296 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
288297 javaVersion = "1.6.0";
289 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
290 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
291 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
292 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
293 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
294 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
295 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
296 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
298 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
299 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
300 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
301 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
302 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
303 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
304 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
305 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
297306 javaVersion = "1.7.0";
298 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
299 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
300 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
301 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
302 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
303 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
304 assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
305 assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
306 }
307
307 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
308 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
309 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
310 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
311 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
312 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
313 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
314 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
315 }
316
317 @Test
308318 public void testOSMatchesName() {
309319 String osName = null;
310 assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
320 assertFalse(SystemUtils.isOSNameMatch(osName, "Windows"));
311321 osName = "";
312 assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
322 assertFalse(SystemUtils.isOSNameMatch(osName, "Windows"));
313323 osName = "Windows 95";
314 assertEquals(true, SystemUtils.isOSNameMatch(osName, "Windows"));
324 assertTrue(SystemUtils.isOSNameMatch(osName, "Windows"));
315325 osName = "Windows NT";
316 assertEquals(true, SystemUtils.isOSNameMatch(osName, "Windows"));
326 assertTrue(SystemUtils.isOSNameMatch(osName, "Windows"));
317327 osName = "OS/2";
318 assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
319 }
320
328 assertFalse(SystemUtils.isOSNameMatch(osName, "Windows"));
329 }
330
331 @Test
321332 public void testOSMatchesNameAndVersion() {
322333 String osName = null;
323334 String osVersion = null;
324 assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
335 assertFalse(SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
325336 osName = "";
326337 osVersion = "";
327 assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
338 assertFalse(SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
328339 osName = "Windows 95";
329340 osVersion = "4.0";
330 assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
341 assertFalse(SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
331342 osName = "Windows 95";
332343 osVersion = "4.1";
333 assertEquals(true, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
344 assertTrue(SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
334345 osName = "Windows 98";
335346 osVersion = "4.1";
336 assertEquals(true, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
347 assertTrue(SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
337348 osName = "Windows NT";
338349 osVersion = "4.0";
339 assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
350 assertFalse(SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
340351 osName = "OS/2";
341352 osVersion = "4.0";
342 assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
343 }
344
353 assertFalse(SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
354 }
355
356 @Test
345357 public void testJavaAwtHeadless() {
346 boolean atLeastJava14 = SystemUtils.isJavaVersionAtLeast(JAVA_1_4);
347 String expectedStringValue = System.getProperty("java.awt.headless");
348 String expectedStringValueWithDefault = System.getProperty("java.awt.headless", "false");
358 final boolean atLeastJava14 = SystemUtils.isJavaVersionAtLeast(JAVA_1_4);
359 final String expectedStringValue = System.getProperty("java.awt.headless");
360 final String expectedStringValueWithDefault = System.getProperty("java.awt.headless", "false");
349361 assertNotNull(expectedStringValueWithDefault);
350362 if (atLeastJava14) {
351 boolean expectedValue = Boolean.valueOf(expectedStringValue).booleanValue();
363 final boolean expectedValue = Boolean.valueOf(expectedStringValue).booleanValue();
352364 if (expectedStringValue != null) {
353365 assertEquals(expectedStringValue, SystemUtils.JAVA_AWT_HEADLESS);
354366 }
1717 */
1818 package org.apache.commons.lang3;
1919
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertNotNull;
23 import static org.junit.Assert.assertSame;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
26
2027 import java.lang.reflect.Constructor;
2128 import java.lang.reflect.Modifier;
2229 import java.util.AbstractList;
2734 import java.util.List;
2835 import java.util.Map;
2936
30 import junit.framework.TestCase;
37 import org.junit.Test;
3138
3239 /**
3340 * Unit tests {@link org.apache.commons.lang3.Validate}.
3441 *
35 * @version $Id: ValidateTest.java 1199726 2011-11-09 12:59:24Z sebb $
42 * @version $Id: ValidateTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3643 */
37 public class ValidateTest extends TestCase {
38
39 public ValidateTest(String name) {
40 super(name);
41 }
42
43 //-----------------------------------------------------------------------
44 public class ValidateTest {
45
46 //-----------------------------------------------------------------------
47 @Test
4448 public void testIsTrue1() {
4549 Validate.isTrue(true);
4650 try {
4751 Validate.isTrue(false);
4852 fail("Expecting IllegalArgumentException");
49 } catch (IllegalArgumentException ex) {
53 } catch (final IllegalArgumentException ex) {
5054 assertEquals("The validated expression is false", ex.getMessage());
5155 }
5256 }
5357
5458 //-----------------------------------------------------------------------
59 @Test
5560 public void testIsTrue2() {
5661 Validate.isTrue(true, "MSG");
5762 try {
5863 Validate.isTrue(false, "MSG");
5964 fail("Expecting IllegalArgumentException");
60 } catch (IllegalArgumentException ex) {
61 assertEquals("MSG", ex.getMessage());
62 }
63 }
64
65 //-----------------------------------------------------------------------
65 } catch (final IllegalArgumentException ex) {
66 assertEquals("MSG", ex.getMessage());
67 }
68 }
69
70 //-----------------------------------------------------------------------
71 @Test
6672 public void testIsTrue3() {
6773 Validate.isTrue(true, "MSG", 6);
6874 try {
6975 Validate.isTrue(false, "MSG", 6);
7076 fail("Expecting IllegalArgumentException");
71 } catch (IllegalArgumentException ex) {
72 assertEquals("MSG", ex.getMessage());
73 }
74 }
75
76 //-----------------------------------------------------------------------
77 } catch (final IllegalArgumentException ex) {
78 assertEquals("MSG", ex.getMessage());
79 }
80 }
81
82 //-----------------------------------------------------------------------
83 @Test
7784 public void testIsTrue4() {
7885 Validate.isTrue(true, "MSG", 7);
7986 try {
8087 Validate.isTrue(false, "MSG", 7);
8188 fail("Expecting IllegalArgumentException");
82 } catch (IllegalArgumentException ex) {
83 assertEquals("MSG", ex.getMessage());
84 }
85 }
86
87 //-----------------------------------------------------------------------
89 } catch (final IllegalArgumentException ex) {
90 assertEquals("MSG", ex.getMessage());
91 }
92 }
93
94 //-----------------------------------------------------------------------
95 @Test
8896 public void testIsTrue5() {
8997 Validate.isTrue(true, "MSG", 7.4d);
9098 try {
9199 Validate.isTrue(false, "MSG", 7.4d);
92100 fail("Expecting IllegalArgumentException");
93 } catch (IllegalArgumentException ex) {
94 assertEquals("MSG", ex.getMessage());
95 }
96 }
97
98 //-----------------------------------------------------------------------
99 //-----------------------------------------------------------------------
101 } catch (final IllegalArgumentException ex) {
102 assertEquals("MSG", ex.getMessage());
103 }
104 }
105
106 //-----------------------------------------------------------------------
107 //-----------------------------------------------------------------------
108 @Test
100109 public void testNotNull1() {
101110 Validate.notNull(new Object());
102111 try {
103112 Validate.notNull(null);
104113 fail("Expecting NullPointerException");
105 } catch (NullPointerException ex) {
114 } catch (final NullPointerException ex) {
106115 assertEquals("The validated object is null", ex.getMessage());
107116 }
108117
109 String str = "Hi";
110 String testStr = Validate.notNull(str);
118 final String str = "Hi";
119 final String testStr = Validate.notNull(str);
111120 assertSame(str, testStr);
112121 }
113122
114123 //-----------------------------------------------------------------------
124 @Test
115125 public void testNotNull2() {
116126 Validate.notNull(new Object(), "MSG");
117127 try {
118128 Validate.notNull(null, "MSG");
119129 fail("Expecting NullPointerException");
120 } catch (NullPointerException ex) {
121 assertEquals("MSG", ex.getMessage());
122 }
123
124 String str = "Hi";
125 String testStr = Validate.notNull(str, "Message");
130 } catch (final NullPointerException ex) {
131 assertEquals("MSG", ex.getMessage());
132 }
133
134 final String str = "Hi";
135 final String testStr = Validate.notNull(str, "Message");
126136 assertSame(str, testStr);
127137 }
128138
129139 //-----------------------------------------------------------------------
130140 //-----------------------------------------------------------------------
141 @Test
131142 public void testNotEmptyArray1() {
132143 Validate.notEmpty(new Object[] {null});
133144 try {
134145 Validate.notEmpty((Object[]) null);
135146 fail("Expecting NullPointerException");
136 } catch (NullPointerException ex) {
147 } catch (final NullPointerException ex) {
137148 assertEquals("The validated array is empty", ex.getMessage());
138149 }
139150 try {
140151 Validate.notEmpty(new Object[0]);
141152 fail("Expecting IllegalArgumentException");
142 } catch (IllegalArgumentException ex) {
153 } catch (final IllegalArgumentException ex) {
143154 assertEquals("The validated array is empty", ex.getMessage());
144155 }
145156
146 String[] array = new String[] {"hi"};
147 String[] test = Validate.notEmpty(array);
157 final String[] array = new String[] {"hi"};
158 final String[] test = Validate.notEmpty(array);
148159 assertSame(array, test);
149160 }
150161
151162 //-----------------------------------------------------------------------
163 @Test
152164 public void testNotEmptyArray2() {
153165 Validate.notEmpty(new Object[] {null}, "MSG");
154166 try {
155167 Validate.notEmpty((Object[]) null, "MSG");
156168 fail("Expecting NullPointerException");
157 } catch (NullPointerException ex) {
169 } catch (final NullPointerException ex) {
158170 assertEquals("MSG", ex.getMessage());
159171 }
160172 try {
161173 Validate.notEmpty(new Object[0], "MSG");
162174 fail("Expecting IllegalArgumentException");
163 } catch (IllegalArgumentException ex) {
164 assertEquals("MSG", ex.getMessage());
165 }
166
167 String[] array = new String[] {"hi"};
168 String[] test = Validate.notEmpty(array, "Message");
175 } catch (final IllegalArgumentException ex) {
176 assertEquals("MSG", ex.getMessage());
177 }
178
179 final String[] array = new String[] {"hi"};
180 final String[] test = Validate.notEmpty(array, "Message");
169181 assertSame(array, test);
170182 }
171183
172184 //-----------------------------------------------------------------------
173185 //-----------------------------------------------------------------------
186 @Test
174187 public void testNotEmptyCollection1() {
175 Collection<Integer> coll = new ArrayList<Integer>();
188 final Collection<Integer> coll = new ArrayList<Integer>();
176189 try {
177190 Validate.notEmpty((Collection<?>) null);
178191 fail("Expecting NullPointerException");
179 } catch (NullPointerException ex) {
192 } catch (final NullPointerException ex) {
180193 assertEquals("The validated collection is empty", ex.getMessage());
181194 }
182195 try {
183196 Validate.notEmpty(coll);
184197 fail("Expecting IllegalArgumentException");
185 } catch (IllegalArgumentException ex) {
198 } catch (final IllegalArgumentException ex) {
186199 assertEquals("The validated collection is empty", ex.getMessage());
187200 }
188201 coll.add(Integer.valueOf(8));
189202 Validate.notEmpty(coll);
190203
191 Collection<Integer> test = Validate.notEmpty(coll);
204 final Collection<Integer> test = Validate.notEmpty(coll);
192205 assertSame(coll, test);
193206 }
194207
195208 //-----------------------------------------------------------------------
209 @Test
196210 public void testNotEmptyCollection2() {
197 Collection<Integer> coll = new ArrayList<Integer>();
211 final Collection<Integer> coll = new ArrayList<Integer>();
198212 try {
199213 Validate.notEmpty((Collection<?>) null, "MSG");
200214 fail("Expecting NullPointerException");
201 } catch (NullPointerException ex) {
215 } catch (final NullPointerException ex) {
202216 assertEquals("MSG", ex.getMessage());
203217 }
204218 try {
205219 Validate.notEmpty(coll, "MSG");
206220 fail("Expecting IllegalArgumentException");
207 } catch (IllegalArgumentException ex) {
221 } catch (final IllegalArgumentException ex) {
208222 assertEquals("MSG", ex.getMessage());
209223 }
210224 coll.add(Integer.valueOf(8));
211225 Validate.notEmpty(coll, "MSG");
212226
213 Collection<Integer> test = Validate.notEmpty(coll, "Message");
227 final Collection<Integer> test = Validate.notEmpty(coll, "Message");
214228 assertSame(coll, test);
215229 }
216230
217231 //-----------------------------------------------------------------------
218232 //-----------------------------------------------------------------------
233 @Test
219234 public void testNotEmptyMap1() {
220 Map<String, Integer> map = new HashMap<String, Integer>();
235 final Map<String, Integer> map = new HashMap<String, Integer>();
221236 try {
222237 Validate.notEmpty((Map<?, ?>) null);
223238 fail("Expecting NullPointerException");
224 } catch (NullPointerException ex) {
239 } catch (final NullPointerException ex) {
225240 assertEquals("The validated map is empty", ex.getMessage());
226241 }
227242 try {
228243 Validate.notEmpty(map);
229244 fail("Expecting IllegalArgumentException");
230 } catch (IllegalArgumentException ex) {
245 } catch (final IllegalArgumentException ex) {
231246 assertEquals("The validated map is empty", ex.getMessage());
232247 }
233248 map.put("ll", Integer.valueOf(8));
234249 Validate.notEmpty(map);
235250
236 Map<String, Integer> test = Validate.notEmpty(map);
251 final Map<String, Integer> test = Validate.notEmpty(map);
237252 assertSame(map, test);
238253 }
239254
240255 //-----------------------------------------------------------------------
256 @Test
241257 public void testNotEmptyMap2() {
242 Map<String, Integer> map = new HashMap<String, Integer>();
258 final Map<String, Integer> map = new HashMap<String, Integer>();
243259 try {
244260 Validate.notEmpty((Map<?, ?>) null, "MSG");
245261 fail("Expecting NullPointerException");
246 } catch (NullPointerException ex) {
262 } catch (final NullPointerException ex) {
247263 assertEquals("MSG", ex.getMessage());
248264 }
249265 try {
250266 Validate.notEmpty(map, "MSG");
251267 fail("Expecting IllegalArgumentException");
252 } catch (IllegalArgumentException ex) {
268 } catch (final IllegalArgumentException ex) {
253269 assertEquals("MSG", ex.getMessage());
254270 }
255271 map.put("ll", Integer.valueOf(8));
256272 Validate.notEmpty(map, "MSG");
257273
258 Map<String, Integer> test = Validate.notEmpty(map, "Message");
274 final Map<String, Integer> test = Validate.notEmpty(map, "Message");
259275 assertSame(map, test);
260276 }
261277
262278 //-----------------------------------------------------------------------
263279 //-----------------------------------------------------------------------
280 @Test
264281 public void testNotEmptyString1() {
265282 Validate.notEmpty("hjl");
266283 try {
267284 Validate.notEmpty((String) null);
268285 fail("Expecting NullPointerException");
269 } catch (NullPointerException ex) {
286 } catch (final NullPointerException ex) {
270287 assertEquals("The validated character sequence is empty", ex.getMessage());
271288 }
272289 try {
273290 Validate.notEmpty("");
274291 fail("Expecting IllegalArgumentException");
275 } catch (IllegalArgumentException ex) {
292 } catch (final IllegalArgumentException ex) {
276293 assertEquals("The validated character sequence is empty", ex.getMessage());
277294 }
278295
279 String str = "Hi";
280 String testStr = Validate.notEmpty(str);
296 final String str = "Hi";
297 final String testStr = Validate.notEmpty(str);
281298 assertSame(str, testStr);
282299 }
283300
284301 //-----------------------------------------------------------------------
302 @Test
285303 public void testNotEmptyString2() {
286304 Validate.notEmpty("a", "MSG");
287305 try {
288306 Validate.notEmpty((String) null, "MSG");
289307 fail("Expecting NullPointerException");
290 } catch (NullPointerException ex) {
308 } catch (final NullPointerException ex) {
291309 assertEquals("MSG", ex.getMessage());
292310 }
293311 try {
294312 Validate.notEmpty("", "MSG");
295313 fail("Expecting IllegalArgumentException");
296 } catch (IllegalArgumentException ex) {
297 assertEquals("MSG", ex.getMessage());
298 }
299
300 String str = "Hi";
301 String testStr = Validate.notEmpty(str, "Message");
314 } catch (final IllegalArgumentException ex) {
315 assertEquals("MSG", ex.getMessage());
316 }
317
318 final String str = "Hi";
319 final String testStr = Validate.notEmpty(str, "Message");
302320 assertSame(str, testStr);
303321 }
304322
305323 //-----------------------------------------------------------------------
306324 //-----------------------------------------------------------------------
325 @Test
307326 public void testNotBlankNullStringShouldThrow() {
308327 //given
309 String string = null;
328 final String string = null;
310329
311330 try {
312331 //when
313332 Validate.notBlank(string);
314333 fail("Expecting NullPointerException");
315 } catch (NullPointerException e) {
334 } catch (final NullPointerException e) {
316335 //then
317336 assertEquals("The validated character sequence is blank", e.getMessage());
318337 }
319338 }
320339
321340 //-----------------------------------------------------------------------
341 @Test
322342 public void testNotBlankMsgNullStringShouldThrow() {
323343 //given
324 String string = null;
344 final String string = null;
325345
326346 try {
327347 //when
328348 Validate.notBlank(string, "Message");
329349 fail("Expecting NullPointerException");
330 } catch (NullPointerException e) {
350 } catch (final NullPointerException e) {
331351 //then
332352 assertEquals("Message", e.getMessage());
333353 }
334354 }
335355
336356 //-----------------------------------------------------------------------
357 @Test
337358 public void testNotBlankEmptyStringShouldThrow() {
338359 //given
339 String string = "";
360 final String string = "";
340361
341362 try {
342363 //when
343364 Validate.notBlank(string);
344365 fail("Expecting IllegalArgumentException");
345 } catch (IllegalArgumentException e) {
366 } catch (final IllegalArgumentException e) {
346367 //then
347368 assertEquals("The validated character sequence is blank", e.getMessage());
348369 }
349370 }
350371
351372 //-----------------------------------------------------------------------
373 @Test
352374 public void testNotBlankBlankStringWithWhitespacesShouldThrow() {
353375 //given
354 String string = " ";
376 final String string = " ";
355377
356378 try {
357379 //when
358380 Validate.notBlank(string);
359381 fail("Expecting IllegalArgumentException");
360 } catch (IllegalArgumentException e) {
382 } catch (final IllegalArgumentException e) {
361383 //then
362384 assertEquals("The validated character sequence is blank", e.getMessage());
363385 }
364386 }
365387
366388 //-----------------------------------------------------------------------
389 @Test
367390 public void testNotBlankBlankStringWithNewlinesShouldThrow() {
368391 //given
369 String string = " \n \t \r \n ";
392 final String string = " \n \t \r \n ";
370393
371394 try {
372395 //when
373396 Validate.notBlank(string);
374397 fail("Expecting IllegalArgumentException");
375 } catch (IllegalArgumentException e) {
398 } catch (final IllegalArgumentException e) {
376399 //then
377400 assertEquals("The validated character sequence is blank", e.getMessage());
378401 }
379402 }
380403
381404 //-----------------------------------------------------------------------
405 @Test
382406 public void testNotBlankMsgBlankStringShouldThrow() {
383407 //given
384 String string = " \n \t \r \n ";
408 final String string = " \n \t \r \n ";
385409
386410 try {
387411 //when
388412 Validate.notBlank(string, "Message");
389413 fail("Expecting IllegalArgumentException");
390 } catch (IllegalArgumentException e) {
414 } catch (final IllegalArgumentException e) {
391415 //then
392416 assertEquals("Message", e.getMessage());
393417 }
394418 }
395419
396420 //-----------------------------------------------------------------------
421 @Test
397422 public void testNotBlankMsgBlankStringWithWhitespacesShouldThrow() {
398423 //given
399 String string = " ";
424 final String string = " ";
400425
401426 try {
402427 //when
403428 Validate.notBlank(string, "Message");
404429 fail("Expecting IllegalArgumentException");
405 } catch (IllegalArgumentException e) {
430 } catch (final IllegalArgumentException e) {
406431 //then
407432 assertEquals("Message", e.getMessage());
408433 }
409434 }
410435
411436 //-----------------------------------------------------------------------
437 @Test
412438 public void testNotBlankMsgEmptyStringShouldThrow() {
413439 //given
414 String string = "";
440 final String string = "";
415441
416442 try {
417443 //when
418444 Validate.notBlank(string, "Message");
419445 fail("Expecting IllegalArgumentException");
420 } catch (IllegalArgumentException e) {
446 } catch (final IllegalArgumentException e) {
421447 //then
422448 assertEquals("Message", e.getMessage());
423449 }
424450 }
425451
426452 //-----------------------------------------------------------------------
453 @Test
427454 public void testNotBlankNotBlankStringShouldNotThrow() {
428455 //given
429 String string = "abc";
456 final String string = "abc";
430457
431458 //when
432459 Validate.notBlank(string);
435462 }
436463
437464 //-----------------------------------------------------------------------
465 @Test
438466 public void testNotBlankNotBlankStringWithWhitespacesShouldNotThrow() {
439467 //given
440 String string = " abc ";
468 final String string = " abc ";
441469
442470 //when
443471 Validate.notBlank(string);
446474 }
447475
448476 //-----------------------------------------------------------------------
477 @Test
449478 public void testNotBlankNotBlankStringWithNewlinesShouldNotThrow() {
450479 //given
451 String string = " \n \t abc \r \n ";
480 final String string = " \n \t abc \r \n ";
452481
453482 //when
454483 Validate.notBlank(string);
457486 }
458487
459488 //-----------------------------------------------------------------------
489 @Test
460490 public void testNotBlankMsgNotBlankStringShouldNotThrow() {
461491 //given
462 String string = "abc";
492 final String string = "abc";
463493
464494 //when
465495 Validate.notBlank(string, "Message");
468498 }
469499
470500 //-----------------------------------------------------------------------
501 @Test
471502 public void testNotBlankMsgNotBlankStringWithWhitespacesShouldNotThrow() {
472503 //given
473 String string = " abc ";
504 final String string = " abc ";
474505
475506 //when
476507 Validate.notBlank(string, "Message");
479510 }
480511
481512 //-----------------------------------------------------------------------
513 @Test
482514 public void testNotBlankMsgNotBlankStringWithNewlinesShouldNotThrow() {
483515 //given
484 String string = " \n \t abc \r \n ";
516 final String string = " \n \t abc \r \n ";
485517
486518 //when
487519 Validate.notBlank(string, "Message");
490522 }
491523
492524 //-----------------------------------------------------------------------
525 @Test
493526 public void testNotBlankReturnValues1() {
494 String str = "Hi";
495 String test = Validate.notBlank(str);
527 final String str = "Hi";
528 final String test = Validate.notBlank(str);
496529 assertSame(str, test);
497530 }
498531
532 @Test
499533 public void testNotBlankReturnValues2() {
500 String str = "Hi";
501 String test = Validate.notBlank(str, "Message");
534 final String str = "Hi";
535 final String test = Validate.notBlank(str, "Message");
502536 assertSame(str, test);
503537 }
504538
505539 //-----------------------------------------------------------------------
506540 //-----------------------------------------------------------------------
541 @Test
507542 public void testNoNullElementsArray1() {
508543 String[] array = new String[] {"a", "b"};
509544 Validate.noNullElements(array);
510545 try {
511546 Validate.noNullElements((Object[]) null);
512547 fail("Expecting NullPointerException");
513 } catch (NullPointerException ex) {
548 } catch (final NullPointerException ex) {
514549 assertEquals("The validated object is null", ex.getMessage());
515550 }
516551 array[1] = null;
517552 try {
518553 Validate.noNullElements(array);
519554 fail("Expecting IllegalArgumentException");
520 } catch (IllegalArgumentException ex) {
555 } catch (final IllegalArgumentException ex) {
521556 assertEquals("The validated array contains null element at index: 1", ex.getMessage());
522557 }
523558
524559 array = new String[] {"a", "b"};
525 String[] test = Validate.noNullElements(array);
560 final String[] test = Validate.noNullElements(array);
526561 assertSame(array, test);
527562 }
528563
529564 //-----------------------------------------------------------------------
565 @Test
530566 public void testNoNullElementsArray2() {
531567 String[] array = new String[] {"a", "b"};
532568 Validate.noNullElements(array, "MSG");
533569 try {
534570 Validate.noNullElements((Object[]) null, "MSG");
535571 fail("Expecting NullPointerException");
536 } catch (NullPointerException ex) {
572 } catch (final NullPointerException ex) {
537573 assertEquals("The validated object is null", ex.getMessage());
538574 }
539575 array[1] = null;
540576 try {
541577 Validate.noNullElements(array, "MSG");
542578 fail("Expecting IllegalArgumentException");
543 } catch (IllegalArgumentException ex) {
579 } catch (final IllegalArgumentException ex) {
544580 assertEquals("MSG", ex.getMessage());
545581 }
546582
547583 array = new String[] {"a", "b"};
548 String[] test = Validate.noNullElements(array, "Message");
584 final String[] test = Validate.noNullElements(array, "Message");
549585 assertSame(array, test);
550586 }
551587
552588 //-----------------------------------------------------------------------
553589 //-----------------------------------------------------------------------
590 @Test
554591 public void testNoNullElementsCollection1() {
555 List<String> coll = new ArrayList<String>();
592 final List<String> coll = new ArrayList<String>();
556593 coll.add("a");
557594 coll.add("b");
558595 Validate.noNullElements(coll);
559596 try {
560597 Validate.noNullElements((Collection<?>) null);
561598 fail("Expecting NullPointerException");
562 } catch (NullPointerException ex) {
599 } catch (final NullPointerException ex) {
563600 assertEquals("The validated object is null", ex.getMessage());
564601 }
565602 coll.set(1, null);
566603 try {
567604 Validate.noNullElements(coll);
568605 fail("Expecting IllegalArgumentException");
569 } catch (IllegalArgumentException ex) {
606 } catch (final IllegalArgumentException ex) {
570607 assertEquals("The validated collection contains null element at index: 1", ex.getMessage());
571608 }
572609
573610 coll.set(1, "b");
574 List<String> test = Validate.noNullElements(coll);
611 final List<String> test = Validate.noNullElements(coll);
575612 assertSame(coll, test);
576613 }
577614
578615 //-----------------------------------------------------------------------
616 @Test
579617 public void testNoNullElementsCollection2() {
580 List<String> coll = new ArrayList<String>();
618 final List<String> coll = new ArrayList<String>();
581619 coll.add("a");
582620 coll.add("b");
583621 Validate.noNullElements(coll, "MSG");
584622 try {
585623 Validate.noNullElements((Collection<?>) null, "MSG");
586624 fail("Expecting NullPointerException");
587 } catch (NullPointerException ex) {
625 } catch (final NullPointerException ex) {
588626 assertEquals("The validated object is null", ex.getMessage());
589627 }
590628 coll.set(1, null);
591629 try {
592630 Validate.noNullElements(coll, "MSG");
593631 fail("Expecting IllegalArgumentException");
594 } catch (IllegalArgumentException ex) {
632 } catch (final IllegalArgumentException ex) {
595633 assertEquals("MSG", ex.getMessage());
596634 }
597635
598636 coll.set(1, "b");
599 List<String> test = Validate.noNullElements(coll, "Message");
637 final List<String> test = Validate.noNullElements(coll, "Message");
600638 assertSame(coll, test);
601639 }
602640
603641 //-----------------------------------------------------------------------
604642 //-----------------------------------------------------------------------
643 @Test
605644 public void testConstructor() {
606645 assertNotNull(new Validate());
607 Constructor<?>[] cons = Validate.class.getDeclaredConstructors();
646 final Constructor<?>[] cons = Validate.class.getDeclaredConstructors();
608647 assertEquals(1, cons.length);
609 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
610 assertEquals(true, Modifier.isPublic(Validate.class.getModifiers()));
611 assertEquals(false, Modifier.isFinal(Validate.class.getModifiers()));
612 }
613
614 //-----------------------------------------------------------------------
615 //-----------------------------------------------------------------------
648 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
649 assertTrue(Modifier.isPublic(Validate.class.getModifiers()));
650 assertFalse(Modifier.isFinal(Validate.class.getModifiers()));
651 }
652
653 //-----------------------------------------------------------------------
654 //-----------------------------------------------------------------------
655 @Test
616656 public void testValidIndex_withMessage_array() {
617 Object[] array = new Object[2];
657 final Object[] array = new Object[2];
618658 Validate.validIndex(array, 0, "Broken: ");
619659 Validate.validIndex(array, 1, "Broken: ");
620660 try {
621661 Validate.validIndex(array, -1, "Broken: ");
622662 fail("Expecting IndexOutOfBoundsException");
623 } catch (IndexOutOfBoundsException ex) {
663 } catch (final IndexOutOfBoundsException ex) {
624664 assertEquals("Broken: ", ex.getMessage());
625665 }
626666 try {
627667 Validate.validIndex(array, 2, "Broken: ");
628668 fail("Expecting IndexOutOfBoundsException");
629 } catch (IndexOutOfBoundsException ex) {
669 } catch (final IndexOutOfBoundsException ex) {
630670 assertEquals("Broken: ", ex.getMessage());
631671 }
632672
633 String[] strArray = new String[] {"Hi"};
634 String[] test = Validate.noNullElements(strArray, "Message");
673 final String[] strArray = new String[] {"Hi"};
674 final String[] test = Validate.noNullElements(strArray, "Message");
635675 assertSame(strArray, test);
636676 }
637677
678 @Test
638679 public void testValidIndex_array() {
639 Object[] array = new Object[2];
680 final Object[] array = new Object[2];
640681 Validate.validIndex(array, 0);
641682 Validate.validIndex(array, 1);
642683 try {
643684 Validate.validIndex(array, -1);
644685 fail("Expecting IndexOutOfBoundsException");
645 } catch (IndexOutOfBoundsException ex) {
686 } catch (final IndexOutOfBoundsException ex) {
646687 assertEquals("The validated array index is invalid: -1", ex.getMessage());
647688 }
648689 try {
649690 Validate.validIndex(array, 2);
650691 fail("Expecting IndexOutOfBoundsException");
651 } catch (IndexOutOfBoundsException ex) {
692 } catch (final IndexOutOfBoundsException ex) {
652693 assertEquals("The validated array index is invalid: 2", ex.getMessage());
653694 }
654695
655 String[] strArray = new String[] {"Hi"};
656 String[] test = Validate.noNullElements(strArray);
696 final String[] strArray = new String[] {"Hi"};
697 final String[] test = Validate.noNullElements(strArray);
657698 assertSame(strArray, test);
658699 }
659700
660701 //-----------------------------------------------------------------------
661702 //-----------------------------------------------------------------------
703 @Test
662704 public void testValidIndex_withMessage_collection() {
663 Collection<String> coll = new ArrayList<String>();
705 final Collection<String> coll = new ArrayList<String>();
664706 coll.add(null);
665707 coll.add(null);
666708 Validate.validIndex(coll, 0, "Broken: ");
668710 try {
669711 Validate.validIndex(coll, -1, "Broken: ");
670712 fail("Expecting IndexOutOfBoundsException");
671 } catch (IndexOutOfBoundsException ex) {
713 } catch (final IndexOutOfBoundsException ex) {
672714 assertEquals("Broken: ", ex.getMessage());
673715 }
674716 try {
675717 Validate.validIndex(coll, 2, "Broken: ");
676718 fail("Expecting IndexOutOfBoundsException");
677 } catch (IndexOutOfBoundsException ex) {
719 } catch (final IndexOutOfBoundsException ex) {
678720 assertEquals("Broken: ", ex.getMessage());
679721 }
680722
681 List<String> strColl = Arrays.asList(new String[] {"Hi"});
682 List<String> test = Validate.validIndex(strColl, 0, "Message");
723 final List<String> strColl = Arrays.asList(new String[] {"Hi"});
724 final List<String> test = Validate.validIndex(strColl, 0, "Message");
683725 assertSame(strColl, test);
684726 }
685727
728 @Test
686729 public void testValidIndex_collection() {
687 Collection<String> coll = new ArrayList<String>();
730 final Collection<String> coll = new ArrayList<String>();
688731 coll.add(null);
689732 coll.add(null);
690733 Validate.validIndex(coll, 0);
692735 try {
693736 Validate.validIndex(coll, -1);
694737 fail("Expecting IndexOutOfBoundsException");
695 } catch (IndexOutOfBoundsException ex) {
738 } catch (final IndexOutOfBoundsException ex) {
696739 assertEquals("The validated collection index is invalid: -1", ex.getMessage());
697740 }
698741 try {
699742 Validate.validIndex(coll, 2);
700743 fail("Expecting IndexOutOfBoundsException");
701 } catch (IndexOutOfBoundsException ex) {
744 } catch (final IndexOutOfBoundsException ex) {
702745 assertEquals("The validated collection index is invalid: 2", ex.getMessage());
703746 }
704747
705 List<String> strColl = Arrays.asList(new String[] {"Hi"});
706 List<String> test = Validate.validIndex(strColl, 0);
748 final List<String> strColl = Arrays.asList(new String[] {"Hi"});
749 final List<String> test = Validate.validIndex(strColl, 0);
707750 assertSame(strColl, test);
708751 }
709752
710753 //-----------------------------------------------------------------------
711754 //-----------------------------------------------------------------------
755 @Test
712756 public void testValidIndex_withMessage_charSequence() {
713 CharSequence str = "Hi";
757 final CharSequence str = "Hi";
714758 Validate.validIndex(str, 0, "Broken: ");
715759 Validate.validIndex(str, 1, "Broken: ");
716760 try {
717761 Validate.validIndex(str, -1, "Broken: ");
718762 fail("Expecting IndexOutOfBoundsException");
719 } catch (IndexOutOfBoundsException ex) {
763 } catch (final IndexOutOfBoundsException ex) {
720764 assertEquals("Broken: ", ex.getMessage());
721765 }
722766 try {
723767 Validate.validIndex(str, 2, "Broken: ");
724768 fail("Expecting IndexOutOfBoundsException");
725 } catch (IndexOutOfBoundsException ex) {
769 } catch (final IndexOutOfBoundsException ex) {
726770 assertEquals("Broken: ", ex.getMessage());
727771 }
728772
729 String input = "Hi";
730 String test = Validate.validIndex(input, 0, "Message");
773 final String input = "Hi";
774 final String test = Validate.validIndex(input, 0, "Message");
731775 assertSame(input, test);
732776 }
733777
778 @Test
734779 public void testValidIndex_charSequence() {
735 CharSequence str = "Hi";
780 final CharSequence str = "Hi";
736781 Validate.validIndex(str, 0);
737782 Validate.validIndex(str, 1);
738783 try {
739784 Validate.validIndex(str, -1);
740785 fail("Expecting IndexOutOfBoundsException");
741 } catch (IndexOutOfBoundsException ex) {
786 } catch (final IndexOutOfBoundsException ex) {
742787 assertEquals("The validated character sequence index is invalid: -1", ex.getMessage());
743788 }
744789 try {
745790 Validate.validIndex(str, 2);
746791 fail("Expecting IndexOutOfBoundsException");
747 } catch (IndexOutOfBoundsException ex) {
792 } catch (final IndexOutOfBoundsException ex) {
748793 assertEquals("The validated character sequence index is invalid: 2", ex.getMessage());
749794 }
750795
751 String input = "Hi";
752 String test = Validate.validIndex(input, 0);
796 final String input = "Hi";
797 final String test = Validate.validIndex(input, 0);
753798 assertSame(input, test);
754799 }
755800
801 @Test
756802 public void testMatchesPattern()
757803 {
758 CharSequence str = "hi";
804 final CharSequence str = "hi";
759805 Validate.matchesPattern(str, "[a-z]*");
760806 try
761807 {
762808 Validate.matchesPattern(str, "[0-9]*");
763809 fail("Expecting IllegalArgumentException");
764810 }
765 catch (IllegalArgumentException e)
811 catch (final IllegalArgumentException e)
766812 {
767813 assertEquals("The string hi does not match the pattern [0-9]*", e.getMessage());
768814 }
769815 }
770816
817 @Test
771818 public void testMatchesPattern_withMessage()
772819 {
773 CharSequence str = "hi";
820 final CharSequence str = "hi";
774821 Validate.matchesPattern(str, "[a-z]*", "Does not match");
775822 try
776823 {
777824 Validate.matchesPattern(str, "[0-9]*", "Does not match");
778825 fail("Expecting IllegalArgumentException");
779826 }
780 catch (IllegalArgumentException e)
827 catch (final IllegalArgumentException e)
781828 {
782829 assertEquals("Does not match", e.getMessage());
783830 }
784831 }
785832
833 @Test
786834 public void testInclusiveBetween()
787835 {
788836 Validate.inclusiveBetween("a", "c", "b");
791839 try {
792840 Validate.inclusiveBetween(0, 5, 6);
793841 fail("Expecting IllegalArgumentException");
794 } catch (IllegalArgumentException e) {
842 } catch (final IllegalArgumentException e) {
795843 assertEquals("The value 6 is not in the specified inclusive range of 0 to 5", e.getMessage());
796844 }
797845 }
798846
847 @Test
799848 public void testInclusiveBetween_withMessage()
800849 {
801850 Validate.inclusiveBetween("a", "c", "b", "Error");
804853 try {
805854 Validate.inclusiveBetween(0, 5, 6, "Error");
806855 fail("Expecting IllegalArgumentException");
807 } catch (IllegalArgumentException e) {
856 } catch (final IllegalArgumentException e) {
808857 assertEquals("Error", e.getMessage());
809858 }
810859 }
811860
861 @Test
812862 public void testExclusiveBetween()
813863 {
814864 Validate.exclusiveBetween("a", "c", "b");
816866 try {
817867 Validate.exclusiveBetween(0, 5, 6);
818868 fail("Expecting IllegalArgumentException");
819 } catch (IllegalArgumentException e) {
869 } catch (final IllegalArgumentException e) {
820870 assertEquals("The value 6 is not in the specified exclusive range of 0 to 5", e.getMessage());
821871 }
822872 try {
823873 Validate.exclusiveBetween(0, 5, 5);
824874 fail("Expecting IllegalArgumentException");
825 } catch (IllegalArgumentException e) {
875 } catch (final IllegalArgumentException e) {
826876 assertEquals("The value 5 is not in the specified exclusive range of 0 to 5", e.getMessage());
827877 }
828878 }
829879
880 @Test
830881 public void testExclusiveBetween_withMessage()
831882 {
832883 Validate.exclusiveBetween("a", "c", "b", "Error");
834885 try {
835886 Validate.exclusiveBetween(0, 5, 6, "Error");
836887 fail("Expecting IllegalArgumentException");
837 } catch (IllegalArgumentException e) {
888 } catch (final IllegalArgumentException e) {
838889 assertEquals("Error", e.getMessage());
839890 }
840891 try {
841892 Validate.exclusiveBetween(0, 5, 5, "Error");
842893 fail("Expecting IllegalArgumentException");
843 } catch (IllegalArgumentException e) {
894 } catch (final IllegalArgumentException e) {
844895 assertEquals("Error", e.getMessage());
845896 }
846897 }
847898
899 @Test
848900 public void testIsInstanceOf() {
849901 Validate.isInstanceOf(String.class, "hi");
850902 Validate.isInstanceOf(Integer.class, 1);
851903 }
852904
905 @Test
853906 public void testIsInstanceOfExceptionMessage() {
854907 try {
855908 Validate.isInstanceOf(List.class, "hi");
856909 fail("Expecting IllegalArgumentException");
857 } catch(IllegalArgumentException e) {
910 } catch(final IllegalArgumentException e) {
858911 assertEquals("Expected type: java.util.List, actual: java.lang.String", e.getMessage());
859912 }
860913 }
861914
915 @Test
862916 public void testIsInstanceOf_withMessage() {
863917 Validate.isInstanceOf(String.class, "hi", "Error");
864918 Validate.isInstanceOf(Integer.class, 1, "Error");
865919 try {
866920 Validate.isInstanceOf(List.class, "hi", "Error");
867921 fail("Expecting IllegalArgumentException");
868 } catch(IllegalArgumentException e) {
922 } catch(final IllegalArgumentException e) {
869923 assertEquals("Error", e.getMessage());
870924 }
871925 }
872926
927 @Test
873928 public void testIsAssignable() {
874929 Validate.isAssignableFrom(CharSequence.class, String.class);
875930 Validate.isAssignableFrom(AbstractList.class, ArrayList.class);
876931 }
877932
933 @Test
878934 public void testIsAssignableExceptionMessage() {
879935 try {
880936 Validate.isAssignableFrom(List.class, String.class);
881937 fail("Expecting IllegalArgumentException");
882 } catch(IllegalArgumentException e) {
938 } catch(final IllegalArgumentException e) {
883939 assertEquals("Cannot assign a java.lang.String to a java.util.List", e.getMessage());
884940 }
885941 }
886942
943 @Test
887944 public void testIsAssignable_withMessage() {
888945 Validate.isAssignableFrom(CharSequence.class, String.class, "Error");
889946 Validate.isAssignableFrom(AbstractList.class, ArrayList.class, "Error");
890947 try {
891948 Validate.isAssignableFrom(List.class, String.class, "Error");
892949 fail("Expecting IllegalArgumentException");
893 } catch(IllegalArgumentException e) {
950 } catch(final IllegalArgumentException e) {
894951 assertEquals("Error", e.getMessage());
895952 }
896953 }
1515 */
1616 package org.apache.commons.lang3.builder;
1717
18 import static org.junit.Assert.assertEquals;
1819 import static org.junit.Assert.assertTrue;
19 import static org.junit.Assert.fail;
2020
2121 import java.math.BigInteger;
2222
2525 /**
2626 * Unit tests {@link org.apache.commons.lang3.builder.CompareToBuilder}.
2727 *
28 * @version $Id: CompareToBuilderTest.java 1199894 2011-11-09 17:53:59Z ggregory $
28 * @version $Id: CompareToBuilderTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2929 */
3030 public class CompareToBuilderTest {
3131
3333
3434 static class TestObject implements Comparable<TestObject> {
3535 private int a;
36 public TestObject(int a) {
36 public TestObject(final int a) {
3737 this.a = a;
3838 }
3939 @Override
40 public boolean equals(Object o) {
40 public boolean equals(final Object o) {
4141 if (o == this) {
4242 return true;
4343 }
4444 if (!(o instanceof TestObject)) {
4545 return false;
4646 }
47 TestObject rhs = (TestObject) o;
47 final TestObject rhs = (TestObject) o;
4848 return a == rhs.a;
4949 }
5050
51 public void setA(int a) {
51 @Override
52 public int hashCode() {
53 return a;
54 }
55
56 public void setA(final int a) {
5257 this.a = a;
5358 }
5459
5560 public int getA() {
5661 return a;
5762 }
58 public int compareTo(TestObject rhs) {
63 @Override
64 public int compareTo(final TestObject rhs) {
5965 return a < rhs.a ? -1 : a > rhs.a ? +1 : 0;
6066 }
6167 }
6571 public TestSubObject() {
6672 super(0);
6773 }
68 public TestSubObject(int a, int b) {
74 public TestSubObject(final int a, final int b) {
6975 super(a);
7076 this.b = b;
7177 }
7278 @Override
73 public boolean equals(Object o) {
79 public boolean equals(final Object o) {
7480 if (o == this) {
7581 return true;
7682 }
7783 if (!(o instanceof TestSubObject)) {
7884 return false;
7985 }
80 TestSubObject rhs = (TestSubObject) o;
86 final TestSubObject rhs = (TestSubObject) o;
8187 return super.equals(o) && b == rhs.b;
8288 }
8389 }
8591 static class TestTransientSubObject extends TestObject {
8692 @SuppressWarnings("unused")
8793 private transient int t;
88 public TestTransientSubObject(int a, int t) {
94 public TestTransientSubObject(final int a, final int t) {
8995 super(a);
9096 this.t = t;
9197 }
9399
94100 @Test
95101 public void testReflectionCompare() {
96 TestObject o1 = new TestObject(4);
97 TestObject o2 = new TestObject(4);
102 final TestObject o1 = new TestObject(4);
103 final TestObject o2 = new TestObject(4);
98104 assertTrue(CompareToBuilder.reflectionCompare(o1, o1) == 0);
99105 assertTrue(CompareToBuilder.reflectionCompare(o1, o2) == 0);
100106 o2.setA(5);
102108 assertTrue(CompareToBuilder.reflectionCompare(o2, o1) > 0);
103109 }
104110
105 @Test
111 @Test(expected=NullPointerException.class)
106112 public void testReflectionCompareEx1() {
107 TestObject o1 = new TestObject(4);
108 try {
109 CompareToBuilder.reflectionCompare(o1, null);
110 } catch (NullPointerException ex) {
111 return;
112 }
113 fail();
114 }
115
116 @Test
113 final TestObject o1 = new TestObject(4);
114 CompareToBuilder.reflectionCompare(o1, null);
115 }
116
117 @Test(expected=ClassCastException.class)
117118 public void testReflectionCompareEx2() {
118 TestObject o1 = new TestObject(4);
119 Object o2 = new Object();
120 try {
121 CompareToBuilder.reflectionCompare(o1, o2);
122 fail();
123 } catch (ClassCastException ex) {}
119 final TestObject o1 = new TestObject(4);
120 final Object o2 = new Object();
121 CompareToBuilder.reflectionCompare(o1, o2);
124122 }
125123
126124 @Test
130128
131129 @Test
132130 public void testReflectionHierarchyCompareExcludeFields() {
133 String[] excludeFields = new String[] { "b" };
131 final String[] excludeFields = new String[] { "b" };
134132 testReflectionHierarchyCompare(true, excludeFields);
135133
136134 TestSubObject x;
167165 assertXYZCompareOrder(x, y, z, true, null);
168166 }
169167
170 private void assertXYZCompareOrder(Object x, Object y, Object z, boolean testTransients, String[] excludeFields) {
168 private void assertXYZCompareOrder(final Object x, final Object y, final Object z, final boolean testTransients, final String[] excludeFields) {
171169 assertTrue(0 == CompareToBuilder.reflectionCompare(x, x, testTransients, null, excludeFields));
172170 assertTrue(0 == CompareToBuilder.reflectionCompare(y, y, testTransients, null, excludeFields));
173171 assertTrue(0 == CompareToBuilder.reflectionCompare(z, z, testTransients, null, excludeFields));
181179 assertTrue(0 < CompareToBuilder.reflectionCompare(z, y, testTransients, null, excludeFields));
182180 }
183181
184 private void testReflectionHierarchyCompare(boolean testTransients, String[] excludeFields) {
185 TestObject to1 = new TestObject(1);
186 TestObject to2 = new TestObject(2);
187 TestObject to3 = new TestObject(3);
188 TestSubObject tso1 = new TestSubObject(1, 1);
189 TestSubObject tso2 = new TestSubObject(2, 2);
190 TestSubObject tso3 = new TestSubObject(3, 3);
182 private void testReflectionHierarchyCompare(final boolean testTransients, final String[] excludeFields) {
183 final TestObject to1 = new TestObject(1);
184 final TestObject to2 = new TestObject(2);
185 final TestObject to3 = new TestObject(3);
186 final TestSubObject tso1 = new TestSubObject(1, 1);
187 final TestSubObject tso2 = new TestSubObject(2, 2);
188 final TestSubObject tso3 = new TestSubObject(3, 3);
191189
192190 assertReflectionCompareContract(to1, to1, to1, false, excludeFields);
193191 assertReflectionCompareContract(to1, to2, to3, false, excludeFields);
213211 * @param testTransients Whether to include transients in the comparison
214212 * @param excludeFields fields to exclude
215213 */
216 private void assertReflectionCompareContract(Object x, Object y, Object z, boolean testTransients, String[] excludeFields) {
214 private void assertReflectionCompareContract(final Object x, final Object y, final Object z, final boolean testTransients, final String[] excludeFields) {
217215
218216 // signum
219217 assertTrue(reflectionCompareSignum(x, y, testTransients, excludeFields) == -reflectionCompareSignum(y, x, testTransients, excludeFields));
243241 * @param excludeFields fields to exclude
244242 * @return int The signum
245243 */
246 private int reflectionCompareSignum(Object lhs, Object rhs, boolean testTransients, String[] excludeFields) {
244 private int reflectionCompareSignum(final Object lhs, final Object rhs, final boolean testTransients, final String[] excludeFields) {
247245 return BigInteger.valueOf(CompareToBuilder.reflectionCompare(lhs, rhs, testTransients)).signum();
248246 }
249247
250248 @Test
251249 public void testAppendSuper() {
252 TestObject o1 = new TestObject(4);
253 TestObject o2 = new TestObject(5);
250 final TestObject o1 = new TestObject(4);
251 final TestObject o2 = new TestObject(5);
254252 assertTrue(new CompareToBuilder().appendSuper(0).append(o1, o1).toComparison() == 0);
255253 assertTrue(new CompareToBuilder().appendSuper(0).append(o1, o2).toComparison() < 0);
256254 assertTrue(new CompareToBuilder().appendSuper(0).append(o2, o1).toComparison() > 0);
264262
265263 @Test
266264 public void testObject() {
267 TestObject o1 = new TestObject(4);
268 TestObject o2 = new TestObject(4);
265 final TestObject o1 = new TestObject(4);
266 final TestObject o2 = new TestObject(4);
269267 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
270268 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() == 0);
271269 o2.setA(5);
279277
280278 @Test
281279 public void testObjectBuild() {
282 TestObject o1 = new TestObject(4);
283 TestObject o2 = new TestObject(4);
284 assertTrue(new CompareToBuilder().append(o1, o1).build() == 0);
285 assertTrue(new CompareToBuilder().append(o1, o2).build() == 0);
280 final TestObject o1 = new TestObject(4);
281 final TestObject o2 = new TestObject(4);
282 assertEquals(Integer.valueOf(0), new CompareToBuilder().append(o1, o1).build());
283 assertEquals(Integer.valueOf(0), new CompareToBuilder().append(o1, o2).build());
286284 o2.setA(5);
287 assertTrue(new CompareToBuilder().append(o1, o2).build() < 0);
288 assertTrue(new CompareToBuilder().append(o2, o1).build() > 0);
289
290 assertTrue(new CompareToBuilder().append(o1, null).build() > 0);
291 assertTrue(new CompareToBuilder().append((Object) null, (Object) null).build() == 0);
292 assertTrue(new CompareToBuilder().append(null, o1).build() < 0);
293 }
294
295 @Test
285 assertTrue(new CompareToBuilder().append(o1, o2).build().intValue() < 0);
286 assertTrue(new CompareToBuilder().append(o2, o1).build().intValue() > 0);
287
288 assertTrue(new CompareToBuilder().append(o1, null).build().intValue() > 0);
289 assertEquals(Integer.valueOf(0), new CompareToBuilder().append((Object) null, (Object) null).build());
290 assertTrue(new CompareToBuilder().append(null, o1).build().intValue() < 0);
291 }
292
293 @Test(expected=ClassCastException.class)
296294 public void testObjectEx2() {
297 TestObject o1 = new TestObject(4);
298 Object o2 = new Object();
299 try {
300 new CompareToBuilder().append(o1, o2);
301 fail();
302 } catch (ClassCastException ex) {}
295 final TestObject o1 = new TestObject(4);
296 final Object o2 = new Object();
297 new CompareToBuilder().append(o1, o2);
303298 }
304299
305300 @Test
306301 public void testObjectComparator() {
307 String o1 = "Fred";
302 final String o1 = "Fred";
308303 String o2 = "Fred";
309304 assertTrue(new CompareToBuilder().append(o1, o1, String.CASE_INSENSITIVE_ORDER).toComparison() == 0);
310305 assertTrue(new CompareToBuilder().append(o1, o2, String.CASE_INSENSITIVE_ORDER).toComparison() == 0);
322317
323318 @Test
324319 public void testObjectComparatorNull() {
325 String o1 = "Fred";
320 final String o1 = "Fred";
326321 String o2 = "Fred";
327322 assertTrue(new CompareToBuilder().append(o1, o1, null).toComparison() == 0);
328323 assertTrue(new CompareToBuilder().append(o1, o2, null).toComparison() == 0);
337332
338333 @Test
339334 public void testLong() {
340 long o1 = 1L;
341 long o2 = 2L;
335 final long o1 = 1L;
336 final long o2 = 2L;
342337 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
343338 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0);
344339 assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0);
350345
351346 @Test
352347 public void testInt() {
353 int o1 = 1;
354 int o2 = 2;
348 final int o1 = 1;
349 final int o2 = 2;
355350 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
356351 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0);
357352 assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0);
363358
364359 @Test
365360 public void testShort() {
366 short o1 = 1;
367 short o2 = 2;
361 final short o1 = 1;
362 final short o2 = 2;
368363 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
369364 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0);
370365 assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0);
376371
377372 @Test
378373 public void testChar() {
379 char o1 = 1;
380 char o2 = 2;
374 final char o1 = 1;
375 final char o2 = 2;
381376 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
382377 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0);
383378 assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0);
389384
390385 @Test
391386 public void testByte() {
392 byte o1 = 1;
393 byte o2 = 2;
387 final byte o1 = 1;
388 final byte o2 = 2;
394389 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
395390 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0);
396391 assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0);
402397
403398 @Test
404399 public void testDouble() {
405 double o1 = 1;
406 double o2 = 2;
400 final double o1 = 1;
401 final double o2 = 2;
407402 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
408403 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0);
409404 assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0);
423418
424419 @Test
425420 public void testFloat() {
426 float o1 = 1;
427 float o2 = 2;
421 final float o1 = 1;
422 final float o2 = 2;
428423 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
429424 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0);
430425 assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0);
444439
445440 @Test
446441 public void testBoolean() {
447 boolean o1 = true;
448 boolean o2 = false;
442 final boolean o1 = true;
443 final boolean o2 = false;
449444 assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0);
450445 assertTrue(new CompareToBuilder().append(o2, o2).toComparison() == 0);
451446 assertTrue(new CompareToBuilder().append(o1, o2).toComparison() > 0);
454449
455450 @Test
456451 public void testObjectArray() {
457 TestObject[] obj1 = new TestObject[2];
452 final TestObject[] obj1 = new TestObject[2];
458453 obj1[0] = new TestObject(4);
459454 obj1[1] = new TestObject(5);
460 TestObject[] obj2 = new TestObject[2];
455 final TestObject[] obj2 = new TestObject[2];
461456 obj2[0] = new TestObject(4);
462457 obj2[1] = new TestObject(5);
463 TestObject[] obj3 = new TestObject[3];
458 final TestObject[] obj3 = new TestObject[3];
464459 obj3[0] = new TestObject(4);
465460 obj3[1] = new TestObject(5);
466461 obj3[2] = new TestObject(6);
481476
482477 @Test
483478 public void testLongArray() {
484 long[] obj1 = new long[2];
479 final long[] obj1 = new long[2];
485480 obj1[0] = 5L;
486481 obj1[1] = 6L;
487 long[] obj2 = new long[2];
482 final long[] obj2 = new long[2];
488483 obj2[0] = 5L;
489484 obj2[1] = 6L;
490 long[] obj3 = new long[3];
485 final long[] obj3 = new long[3];
491486 obj3[0] = 5L;
492487 obj3[1] = 6L;
493488 obj3[2] = 7L;
508503
509504 @Test
510505 public void testIntArray() {
511 int[] obj1 = new int[2];
506 final int[] obj1 = new int[2];
512507 obj1[0] = 5;
513508 obj1[1] = 6;
514 int[] obj2 = new int[2];
509 final int[] obj2 = new int[2];
515510 obj2[0] = 5;
516511 obj2[1] = 6;
517 int[] obj3 = new int[3];
512 final int[] obj3 = new int[3];
518513 obj3[0] = 5;
519514 obj3[1] = 6;
520515 obj3[2] = 7;
535530
536531 @Test
537532 public void testShortArray() {
538 short[] obj1 = new short[2];
533 final short[] obj1 = new short[2];
539534 obj1[0] = 5;
540535 obj1[1] = 6;
541 short[] obj2 = new short[2];
536 final short[] obj2 = new short[2];
542537 obj2[0] = 5;
543538 obj2[1] = 6;
544 short[] obj3 = new short[3];
539 final short[] obj3 = new short[3];
545540 obj3[0] = 5;
546541 obj3[1] = 6;
547542 obj3[2] = 7;
562557
563558 @Test
564559 public void testCharArray() {
565 char[] obj1 = new char[2];
560 final char[] obj1 = new char[2];
566561 obj1[0] = 5;
567562 obj1[1] = 6;
568 char[] obj2 = new char[2];
563 final char[] obj2 = new char[2];
569564 obj2[0] = 5;
570565 obj2[1] = 6;
571 char[] obj3 = new char[3];
566 final char[] obj3 = new char[3];
572567 obj3[0] = 5;
573568 obj3[1] = 6;
574569 obj3[2] = 7;
589584
590585 @Test
591586 public void testByteArray() {
592 byte[] obj1 = new byte[2];
587 final byte[] obj1 = new byte[2];
593588 obj1[0] = 5;
594589 obj1[1] = 6;
595 byte[] obj2 = new byte[2];
590 final byte[] obj2 = new byte[2];
596591 obj2[0] = 5;
597592 obj2[1] = 6;
598 byte[] obj3 = new byte[3];
593 final byte[] obj3 = new byte[3];
599594 obj3[0] = 5;
600595 obj3[1] = 6;
601596 obj3[2] = 7;
616611
617612 @Test
618613 public void testDoubleArray() {
619 double[] obj1 = new double[2];
614 final double[] obj1 = new double[2];
620615 obj1[0] = 5;
621616 obj1[1] = 6;
622 double[] obj2 = new double[2];
617 final double[] obj2 = new double[2];
623618 obj2[0] = 5;
624619 obj2[1] = 6;
625 double[] obj3 = new double[3];
620 final double[] obj3 = new double[3];
626621 obj3[0] = 5;
627622 obj3[1] = 6;
628623 obj3[2] = 7;
643638
644639 @Test
645640 public void testFloatArray() {
646 float[] obj1 = new float[2];
641 final float[] obj1 = new float[2];
647642 obj1[0] = 5;
648643 obj1[1] = 6;
649 float[] obj2 = new float[2];
644 final float[] obj2 = new float[2];
650645 obj2[0] = 5;
651646 obj2[1] = 6;
652 float[] obj3 = new float[3];
647 final float[] obj3 = new float[3];
653648 obj3[0] = 5;
654649 obj3[1] = 6;
655650 obj3[2] = 7;
670665
671666 @Test
672667 public void testBooleanArray() {
673 boolean[] obj1 = new boolean[2];
668 final boolean[] obj1 = new boolean[2];
674669 obj1[0] = true;
675670 obj1[1] = false;
676 boolean[] obj2 = new boolean[2];
671 final boolean[] obj2 = new boolean[2];
677672 obj2[0] = true;
678673 obj2[1] = false;
679 boolean[] obj3 = new boolean[3];
674 final boolean[] obj3 = new boolean[3];
680675 obj3[0] = true;
681676 obj3[1] = false;
682677 obj3[2] = true;
697692
698693 @Test
699694 public void testMultiLongArray() {
700 long[][] array1 = new long[2][2];
701 long[][] array2 = new long[2][2];
702 long[][] array3 = new long[2][3];
695 final long[][] array1 = new long[2][2];
696 final long[][] array2 = new long[2][2];
697 final long[][] array3 = new long[2][3];
703698 for (int i = 0; i < array1.length; ++i) {
704699 for (int j = 0; j < array1[0].length; j++) {
705700 array1[i][j] = (i + 1) * (j + 1);
721716
722717 @Test
723718 public void testMultiIntArray() {
724 int[][] array1 = new int[2][2];
725 int[][] array2 = new int[2][2];
726 int[][] array3 = new int[2][3];
719 final int[][] array1 = new int[2][2];
720 final int[][] array2 = new int[2][2];
721 final int[][] array3 = new int[2][3];
727722 for (int i = 0; i < array1.length; ++i) {
728723 for (int j = 0; j < array1[0].length; j++) {
729724 array1[i][j] = (i + 1) * (j + 1);
745740
746741 @Test
747742 public void testMultiShortArray() {
748 short[][] array1 = new short[2][2];
749 short[][] array2 = new short[2][2];
750 short[][] array3 = new short[2][3];
743 final short[][] array1 = new short[2][2];
744 final short[][] array2 = new short[2][2];
745 final short[][] array3 = new short[2][3];
751746 for (short i = 0; i < array1.length; ++i) {
752747 for (short j = 0; j < array1[0].length; j++) {
753748 array1[i][j] = (short)((i + 1) * (j + 1));
769764
770765 @Test
771766 public void testMultiCharArray() {
772 char[][] array1 = new char[2][2];
773 char[][] array2 = new char[2][2];
774 char[][] array3 = new char[2][3];
767 final char[][] array1 = new char[2][2];
768 final char[][] array2 = new char[2][2];
769 final char[][] array3 = new char[2][3];
775770 for (short i = 0; i < array1.length; ++i) {
776771 for (short j = 0; j < array1[0].length; j++) {
777772 array1[i][j] = (char)((i + 1) * (j + 1));
793788
794789 @Test
795790 public void testMultiByteArray() {
796 byte[][] array1 = new byte[2][2];
797 byte[][] array2 = new byte[2][2];
798 byte[][] array3 = new byte[2][3];
791 final byte[][] array1 = new byte[2][2];
792 final byte[][] array2 = new byte[2][2];
793 final byte[][] array3 = new byte[2][3];
799794 for (byte i = 0; i < array1.length; ++i) {
800795 for (byte j = 0; j < array1[0].length; j++) {
801796 array1[i][j] = (byte)((i + 1) * (j + 1));
817812
818813 @Test
819814 public void testMultiFloatArray() {
820 float[][] array1 = new float[2][2];
821 float[][] array2 = new float[2][2];
822 float[][] array3 = new float[2][3];
815 final float[][] array1 = new float[2][2];
816 final float[][] array2 = new float[2][2];
817 final float[][] array3 = new float[2][3];
823818 for (int i = 0; i < array1.length; ++i) {
824819 for (int j = 0; j < array1[0].length; j++) {
825820 array1[i][j] = (i + 1) * (j + 1);
841836
842837 @Test
843838 public void testMultiDoubleArray() {
844 double[][] array1 = new double[2][2];
845 double[][] array2 = new double[2][2];
846 double[][] array3 = new double[2][3];
839 final double[][] array1 = new double[2][2];
840 final double[][] array2 = new double[2][2];
841 final double[][] array3 = new double[2][3];
847842 for (int i = 0; i < array1.length; ++i) {
848843 for (int j = 0; j < array1[0].length; j++) {
849844 array1[i][j] = (i + 1) * (j + 1);
865860
866861 @Test
867862 public void testMultiBooleanArray() {
868 boolean[][] array1 = new boolean[2][2];
869 boolean[][] array2 = new boolean[2][2];
870 boolean[][] array3 = new boolean[2][3];
863 final boolean[][] array1 = new boolean[2][2];
864 final boolean[][] array2 = new boolean[2][2];
865 final boolean[][] array3 = new boolean[2][3];
871866 for (int i = 0; i < array1.length; ++i) {
872867 for (int j = 0; j < array1[0].length; j++) {
873868 array1[i][j] = i == 1 ^ j == 1;
889884
890885 @Test
891886 public void testRaggedArray() {
892 long array1[][] = new long[2][];
893 long array2[][] = new long[2][];
894 long array3[][] = new long[3][];
887 final long array1[][] = new long[2][];
888 final long array2[][] = new long[2][];
889 final long array3[][] = new long[3][];
895890 for (int i = 0; i < array1.length; ++i) {
896891 array1[i] = new long[2];
897892 array2[i] = new long[2];
917912
918913 @Test
919914 public void testMixedArray() {
920 Object array1[] = new Object[2];
921 Object array2[] = new Object[2];
922 Object array3[] = new Object[2];
915 final Object array1[] = new Object[2];
916 final Object array2[] = new Object[2];
917 final Object array3[] = new Object[2];
923918 for (int i = 0; i < array1.length; ++i) {
924919 array1[i] = new long[2];
925920 array2[i] = new long[2];
943938
944939 @Test
945940 public void testObjectArrayHiddenByObject() {
946 TestObject[] array1 = new TestObject[2];
941 final TestObject[] array1 = new TestObject[2];
947942 array1[0] = new TestObject(4);
948943 array1[1] = new TestObject(5);
949 TestObject[] array2 = new TestObject[2];
944 final TestObject[] array2 = new TestObject[2];
950945 array2[0] = new TestObject(4);
951946 array2[1] = new TestObject(5);
952 TestObject[] array3 = new TestObject[3];
947 final TestObject[] array3 = new TestObject[3];
953948 array3[0] = new TestObject(4);
954949 array3[1] = new TestObject(5);
955950 array3[2] = new TestObject(6);
956951
957 Object obj1 = array1;
958 Object obj2 = array2;
959 Object obj3 = array3;
952 final Object obj1 = array1;
953 final Object obj2 = array2;
954 final Object obj3 = array3;
960955
961956 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
962957 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
970965
971966 @Test
972967 public void testLongArrayHiddenByObject() {
973 long[] array1 = new long[2];
968 final long[] array1 = new long[2];
974969 array1[0] = 5L;
975970 array1[1] = 6L;
976 long[] array2 = new long[2];
971 final long[] array2 = new long[2];
977972 array2[0] = 5L;
978973 array2[1] = 6L;
979 long[] array3 = new long[3];
974 final long[] array3 = new long[3];
980975 array3[0] = 5L;
981976 array3[1] = 6L;
982977 array3[2] = 7L;
983 Object obj1 = array1;
984 Object obj2 = array2;
985 Object obj3 = array3;
978 final Object obj1 = array1;
979 final Object obj2 = array2;
980 final Object obj3 = array3;
986981 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
987982 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
988983 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
995990
996991 @Test
997992 public void testIntArrayHiddenByObject() {
998 int[] array1 = new int[2];
993 final int[] array1 = new int[2];
999994 array1[0] = 5;
1000995 array1[1] = 6;
1001 int[] array2 = new int[2];
996 final int[] array2 = new int[2];
1002997 array2[0] = 5;
1003998 array2[1] = 6;
1004 int[] array3 = new int[3];
999 final int[] array3 = new int[3];
10051000 array3[0] = 5;
10061001 array3[1] = 6;
10071002 array3[2] = 7;
1008 Object obj1 = array1;
1009 Object obj2 = array2;
1010 Object obj3 = array3;
1003 final Object obj1 = array1;
1004 final Object obj2 = array2;
1005 final Object obj3 = array3;
10111006 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
10121007 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
10131008 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
10201015
10211016 @Test
10221017 public void testShortArrayHiddenByObject() {
1023 short[] array1 = new short[2];
1018 final short[] array1 = new short[2];
10241019 array1[0] = 5;
10251020 array1[1] = 6;
1026 short[] array2 = new short[2];
1021 final short[] array2 = new short[2];
10271022 array2[0] = 5;
10281023 array2[1] = 6;
1029 short[] array3 = new short[3];
1024 final short[] array3 = new short[3];
10301025 array3[0] = 5;
10311026 array3[1] = 6;
10321027 array3[2] = 7;
1033 Object obj1 = array1;
1034 Object obj2 = array2;
1035 Object obj3 = array3;
1028 final Object obj1 = array1;
1029 final Object obj2 = array2;
1030 final Object obj3 = array3;
10361031 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
10371032 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
10381033 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
10451040
10461041 @Test
10471042 public void testCharArrayHiddenByObject() {
1048 char[] array1 = new char[2];
1043 final char[] array1 = new char[2];
10491044 array1[0] = 5;
10501045 array1[1] = 6;
1051 char[] array2 = new char[2];
1046 final char[] array2 = new char[2];
10521047 array2[0] = 5;
10531048 array2[1] = 6;
1054 char[] array3 = new char[3];
1049 final char[] array3 = new char[3];
10551050 array3[0] = 5;
10561051 array3[1] = 6;
10571052 array3[2] = 7;
1058 Object obj1 = array1;
1059 Object obj2 = array2;
1060 Object obj3 = array3;
1053 final Object obj1 = array1;
1054 final Object obj2 = array2;
1055 final Object obj3 = array3;
10611056 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
10621057 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
10631058 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
10701065
10711066 @Test
10721067 public void testByteArrayHiddenByObject() {
1073 byte[] array1 = new byte[2];
1068 final byte[] array1 = new byte[2];
10741069 array1[0] = 5;
10751070 array1[1] = 6;
1076 byte[] array2 = new byte[2];
1071 final byte[] array2 = new byte[2];
10771072 array2[0] = 5;
10781073 array2[1] = 6;
1079 byte[] array3 = new byte[3];
1074 final byte[] array3 = new byte[3];
10801075 array3[0] = 5;
10811076 array3[1] = 6;
10821077 array3[2] = 7;
1083 Object obj1 = array1;
1084 Object obj2 = array2;
1085 Object obj3 = array3;
1078 final Object obj1 = array1;
1079 final Object obj2 = array2;
1080 final Object obj3 = array3;
10861081 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
10871082 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
10881083 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
10951090
10961091 @Test
10971092 public void testDoubleArrayHiddenByObject() {
1098 double[] array1 = new double[2];
1093 final double[] array1 = new double[2];
10991094 array1[0] = 5;
11001095 array1[1] = 6;
1101 double[] array2 = new double[2];
1096 final double[] array2 = new double[2];
11021097 array2[0] = 5;
11031098 array2[1] = 6;
1104 double[] array3 = new double[3];
1099 final double[] array3 = new double[3];
11051100 array3[0] = 5;
11061101 array3[1] = 6;
11071102 array3[2] = 7;
1108 Object obj1 = array1;
1109 Object obj2 = array2;
1110 Object obj3 = array3;
1103 final Object obj1 = array1;
1104 final Object obj2 = array2;
1105 final Object obj3 = array3;
11111106 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
11121107 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
11131108 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
11201115
11211116 @Test
11221117 public void testFloatArrayHiddenByObject() {
1123 float[] array1 = new float[2];
1118 final float[] array1 = new float[2];
11241119 array1[0] = 5;
11251120 array1[1] = 6;
1126 float[] array2 = new float[2];
1121 final float[] array2 = new float[2];
11271122 array2[0] = 5;
11281123 array2[1] = 6;
1129 float[] array3 = new float[3];
1124 final float[] array3 = new float[3];
11301125 array3[0] = 5;
11311126 array3[1] = 6;
11321127 array3[2] = 7;
1133 Object obj1 = array1;
1134 Object obj2 = array2;
1135 Object obj3 = array3;
1128 final Object obj1 = array1;
1129 final Object obj2 = array2;
1130 final Object obj3 = array3;
11361131 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
11371132 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
11381133 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
11451140
11461141 @Test
11471142 public void testBooleanArrayHiddenByObject() {
1148 boolean[] array1 = new boolean[2];
1143 final boolean[] array1 = new boolean[2];
11491144 array1[0] = true;
11501145 array1[1] = false;
1151 boolean[] array2 = new boolean[2];
1146 final boolean[] array2 = new boolean[2];
11521147 array2[0] = true;
11531148 array2[1] = false;
1154 boolean[] array3 = new boolean[3];
1149 final boolean[] array3 = new boolean[3];
11551150 array3[0] = true;
11561151 array3[1] = false;
11571152 array3[2] = true;
1158 Object obj1 = array1;
1159 Object obj2 = array2;
1160 Object obj3 = array3;
1153 final Object obj1 = array1;
1154 final Object obj2 = array2;
1155 final Object obj3 = array3;
11611156 assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0);
11621157 assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0);
11631158 assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0);
2828 /**
2929 * Unit tests {@link org.apache.commons.lang3.builder.DefaultToStringStyleTest}.
3030 *
31 * @version $Id: DefaultToStringStyleTest.java 1185710 2011-10-18 15:07:07Z ggregory $
31 * @version $Id: DefaultToStringStyleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3232 */
3333 public class DefaultToStringStyleTest {
3434
6464
6565 @Test
6666 public void testObject() {
67 Integer i3 = Integer.valueOf(3);
68 Integer i4 = Integer.valueOf(4);
67 final Integer i3 = Integer.valueOf(3);
68 final Integer i4 = Integer.valueOf(4);
6969 assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).toString());
7070 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString());
7171 assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).toString());
8282
8383 @Test
8484 public void testPerson() {
85 Person p = new Person();
85 final Person p = new Person();
8686 p.name = "John Doe";
8787 p.age = 33;
8888 p.smoker = false;
89 String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p));
89 final String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p));
9090 assertEquals(pBaseStr + "[name=John Doe,age=33,smoker=false]", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString());
9191 }
9292
2727 /**
2828 * Unit tests {@link org.apache.commons.lang3.builder.EqualsBuilder}.
2929 *
30 * @version $Id: EqualsBuilderTest.java 1199894 2011-11-09 17:53:59Z ggregory $
30 * @version $Id: EqualsBuilderTest.java 1535653 2013-10-25 08:19:29Z bayard $
3131 */
3232 public class EqualsBuilderTest {
3333
3737 private int a;
3838 public TestObject() {
3939 }
40 public TestObject(int a) {
40 public TestObject(final int a) {
4141 this.a = a;
4242 }
4343 @Override
44 public boolean equals(Object o) {
44 public boolean equals(final Object o) {
4545 if (o == null) { return false; }
4646 if (o == this) { return true; }
4747 if (o.getClass() != getClass()) {
4848 return false;
4949 }
5050
51 TestObject rhs = (TestObject) o;
51 final TestObject rhs = (TestObject) o;
5252 return a == rhs.a;
5353 }
5454
55 public void setA(int a) {
55 @Override
56 public int hashCode() {
57 return a;
58 }
59
60 public void setA(final int a) {
5661 this.a = a;
5762 }
5863
6671 public TestSubObject() {
6772 super(0);
6873 }
69 public TestSubObject(int a, int b) {
74 public TestSubObject(final int a, final int b) {
7075 super(a);
7176 this.b = b;
7277 }
7378 @Override
74 public boolean equals(Object o) {
79 public boolean equals(final Object o) {
7580 if (o == null) { return false; }
7681 if (o == this) { return true; }
7782 if (o.getClass() != getClass()) {
7883 return false;
7984 }
8085
81 TestSubObject rhs = (TestSubObject) o;
86 final TestSubObject rhs = (TestSubObject) o;
8287 return super.equals(o) && b == rhs.b;
8388 }
8489
85 public void setB(int b) {
90 @Override
91 public int hashCode() {
92 return b *17 + super.hashCode();
93 }
94
95 public void setB(final int b) {
8696 this.b = b;
8797 }
8898
92102 }
93103
94104 static class TestEmptySubObject extends TestObject {
95 public TestEmptySubObject(int a) {
105 public TestEmptySubObject(final int a) {
96106 super(a);
97107 }
98108 }
100110 static class TestTSubObject extends TestObject {
101111 @SuppressWarnings("unused")
102112 private transient int t;
103 public TestTSubObject(int a, int t) {
113 public TestTSubObject(final int a, final int t) {
104114 super(a);
105115 this.t = t;
106116 }
109119 static class TestTTSubObject extends TestTSubObject {
110120 @SuppressWarnings("unused")
111121 private transient int tt;
112 public TestTTSubObject(int a, int t, int tt) {
122 public TestTTSubObject(final int a, final int t, final int tt) {
113123 super(a, t);
114124 this.tt = tt;
115125 }
117127
118128 static class TestTTLeafObject extends TestTTSubObject {
119129 @SuppressWarnings("unused")
120 private int leafValue;
121 public TestTTLeafObject(int a, int t, int tt, int leafValue) {
130 private final int leafValue;
131 public TestTTLeafObject(final int a, final int t, final int tt, final int leafValue) {
122132 super(a, t, tt);
123133 this.leafValue = leafValue;
124134 }
126136
127137 static class TestTSubObject2 extends TestObject {
128138 private transient int t;
129 public TestTSubObject2(int a, int t) {
139 public TestTSubObject2(final int a, final int t) {
130140 super(a);
131141 }
132142 public int getT() {
133143 return t;
134144 }
135 public void setT(int t) {
145 public void setT(final int t) {
136146 this.t = t;
137147 }
138148 }
139149
140150 @Test
141151 public void testReflectionEquals() {
142 TestObject o1 = new TestObject(4);
143 TestObject o2 = new TestObject(5);
152 final TestObject o1 = new TestObject(4);
153 final TestObject o2 = new TestObject(5);
144154 assertTrue(EqualsBuilder.reflectionEquals(o1, o1));
145155 assertTrue(!EqualsBuilder.reflectionEquals(o1, o2));
146156 o2.setA(4);
165175 assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(0, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true));
166176 }
167177
168 private void testReflectionHierarchyEquals(boolean testTransients) {
169 TestObject to1 = new TestObject(4);
170 TestObject to1Bis = new TestObject(4);
171 TestObject to1Ter = new TestObject(4);
172 TestObject to2 = new TestObject(5);
173 TestEmptySubObject teso = new TestEmptySubObject(4);
174 TestTSubObject ttso = new TestTSubObject(4, 1);
175 TestTTSubObject tttso = new TestTTSubObject(4, 1, 2);
176 TestTTLeafObject ttlo = new TestTTLeafObject(4, 1, 2, 3);
177 TestSubObject tso1 = new TestSubObject(1, 4);
178 TestSubObject tso1bis = new TestSubObject(1, 4);
179 TestSubObject tso1ter = new TestSubObject(1, 4);
180 TestSubObject tso2 = new TestSubObject(2, 5);
178 private void testReflectionHierarchyEquals(final boolean testTransients) {
179 final TestObject to1 = new TestObject(4);
180 final TestObject to1Bis = new TestObject(4);
181 final TestObject to1Ter = new TestObject(4);
182 final TestObject to2 = new TestObject(5);
183 final TestEmptySubObject teso = new TestEmptySubObject(4);
184 final TestTSubObject ttso = new TestTSubObject(4, 1);
185 final TestTTSubObject tttso = new TestTTSubObject(4, 1, 2);
186 final TestTTLeafObject ttlo = new TestTTLeafObject(4, 1, 2, 3);
187 final TestSubObject tso1 = new TestSubObject(1, 4);
188 final TestSubObject tso1bis = new TestSubObject(1, 4);
189 final TestSubObject tso1ter = new TestSubObject(1, 4);
190 final TestSubObject tso2 = new TestSubObject(2, 5);
181191
182192 testReflectionEqualsEquivalenceRelationship(to1, to1Bis, to1Ter, to2, new TestObject(), testTransients);
183193 testReflectionEqualsEquivalenceRelationship(tso1, tso1bis, tso1ter, tso2, new TestSubObject(), testTransients);
238248 * @param testTransients whether to test transient instance variables
239249 */
240250 private void testReflectionEqualsEquivalenceRelationship(
241 TestObject to,
242 TestObject toBis,
243 TestObject toTer,
244 TestObject to2,
245 TestObject oToChange,
246 boolean testTransients) {
251 final TestObject to,
252 final TestObject toBis,
253 final TestObject toTer,
254 final TestObject to2,
255 final TestObject oToChange,
256 final boolean testTransients) {
247257
248258 // reflection test
249259 assertTrue(EqualsBuilder.reflectionEquals(to, to, testTransients));
282292
283293 @Test
284294 public void testSuper() {
285 TestObject o1 = new TestObject(4);
286 TestObject o2 = new TestObject(5);
295 final TestObject o1 = new TestObject(4);
296 final TestObject o2 = new TestObject(5);
287297 assertTrue(new EqualsBuilder().appendSuper(true).append(o1, o1).isEquals());
288298 assertFalse(new EqualsBuilder().appendSuper(false).append(o1, o1).isEquals());
289299 assertFalse(new EqualsBuilder().appendSuper(true).append(o1, o2).isEquals());
292302
293303 @Test
294304 public void testObject() {
295 TestObject o1 = new TestObject(4);
296 TestObject o2 = new TestObject(5);
305 final TestObject o1 = new TestObject(4);
306 final TestObject o2 = new TestObject(5);
297307 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
298308 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
299309 o2.setA(4);
308318
309319 @Test
310320 public void testObjectBuild() {
311 TestObject o1 = new TestObject(4);
312 TestObject o2 = new TestObject(5);
321 final TestObject o1 = new TestObject(4);
322 final TestObject o2 = new TestObject(5);
313323 assertEquals(Boolean.TRUE, new EqualsBuilder().append(o1, o1).build());
314324 assertEquals(Boolean.FALSE, new EqualsBuilder().append(o1, o2).build());
315325 o2.setA(4);
324334
325335 @Test
326336 public void testLong() {
327 long o1 = 1L;
328 long o2 = 2L;
337 final long o1 = 1L;
338 final long o2 = 2L;
329339 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
330340 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
331341 }
332342
333343 @Test
334344 public void testInt() {
335 int o1 = 1;
336 int o2 = 2;
345 final int o1 = 1;
346 final int o2 = 2;
337347 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
338348 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
339349 }
340350
341351 @Test
342352 public void testShort() {
343 short o1 = 1;
344 short o2 = 2;
353 final short o1 = 1;
354 final short o2 = 2;
345355 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
346356 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
347357 }
348358
349359 @Test
350360 public void testChar() {
351 char o1 = 1;
352 char o2 = 2;
361 final char o1 = 1;
362 final char o2 = 2;
353363 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
354364 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
355365 }
356366
357367 @Test
358368 public void testByte() {
359 byte o1 = 1;
360 byte o2 = 2;
369 final byte o1 = 1;
370 final byte o2 = 2;
361371 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
362372 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
363373 }
364374
365375 @Test
366376 public void testDouble() {
367 double o1 = 1;
368 double o2 = 2;
377 final double o1 = 1;
378 final double o2 = 2;
369379 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
370380 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
371381 assertTrue(!new EqualsBuilder().append(o1, Double.NaN).isEquals());
375385
376386 @Test
377387 public void testFloat() {
378 float o1 = 1;
379 float o2 = 2;
388 final float o1 = 1;
389 final float o2 = 2;
380390 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
381391 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
382392 assertTrue(!new EqualsBuilder().append(o1, Float.NaN).isEquals());
386396
387397 @Test
388398 public void testAccessors() {
389 EqualsBuilder equalsBuilder = new EqualsBuilder();
399 final EqualsBuilder equalsBuilder = new EqualsBuilder();
390400 assertTrue(equalsBuilder.isEquals());
391401 equalsBuilder.setEquals(true);
392402 assertTrue(equalsBuilder.isEquals());
396406
397407 @Test
398408 public void testReset() {
399 EqualsBuilder equalsBuilder = new EqualsBuilder();
409 final EqualsBuilder equalsBuilder = new EqualsBuilder();
400410 assertTrue(equalsBuilder.isEquals());
401411 equalsBuilder.setEquals(false);
402412 assertFalse(equalsBuilder.isEquals());
406416
407417 @Test
408418 public void testBoolean() {
409 boolean o1 = true;
410 boolean o2 = false;
419 final boolean o1 = true;
420 final boolean o2 = false;
411421 assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
412422 assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
413423 }
595605
596606 @Test
597607 public void testMultiLongArray() {
598 long[][] array1 = new long[2][2];
599 long[][] array2 = new long[2][2];
608 final long[][] array1 = new long[2][2];
609 final long[][] array2 = new long[2][2];
600610 for (int i = 0; i < array1.length; ++i) {
601611 for (int j = 0; j < array1[0].length; j++) {
602612 array1[i][j] = (i + 1) * (j + 1);
611621
612622 @Test
613623 public void testMultiIntArray() {
614 int[][] array1 = new int[2][2];
615 int[][] array2 = new int[2][2];
624 final int[][] array1 = new int[2][2];
625 final int[][] array2 = new int[2][2];
616626 for (int i = 0; i < array1.length; ++i) {
617627 for (int j = 0; j < array1[0].length; j++) {
618628 array1[i][j] = (i + 1) * (j + 1);
627637
628638 @Test
629639 public void testMultiShortArray() {
630 short[][] array1 = new short[2][2];
631 short[][] array2 = new short[2][2];
640 final short[][] array1 = new short[2][2];
641 final short[][] array2 = new short[2][2];
632642 for (short i = 0; i < array1.length; ++i) {
633643 for (short j = 0; j < array1[0].length; j++) {
634644 array1[i][j] = i;
643653
644654 @Test
645655 public void testMultiCharArray() {
646 char[][] array1 = new char[2][2];
647 char[][] array2 = new char[2][2];
656 final char[][] array1 = new char[2][2];
657 final char[][] array2 = new char[2][2];
648658 for (char i = 0; i < array1.length; ++i) {
649659 for (char j = 0; j < array1[0].length; j++) {
650660 array1[i][j] = i;
659669
660670 @Test
661671 public void testMultiByteArray() {
662 byte[][] array1 = new byte[2][2];
663 byte[][] array2 = new byte[2][2];
672 final byte[][] array1 = new byte[2][2];
673 final byte[][] array2 = new byte[2][2];
664674 for (byte i = 0; i < array1.length; ++i) {
665675 for (byte j = 0; j < array1[0].length; j++) {
666676 array1[i][j] = i;
675685
676686 @Test
677687 public void testMultiFloatArray() {
678 float[][] array1 = new float[2][2];
679 float[][] array2 = new float[2][2];
688 final float[][] array1 = new float[2][2];
689 final float[][] array2 = new float[2][2];
680690 for (int i = 0; i < array1.length; ++i) {
681691 for (int j = 0; j < array1[0].length; j++) {
682692 array1[i][j] = (i + 1) * (j + 1);
691701
692702 @Test
693703 public void testMultiDoubleArray() {
694 double[][] array1 = new double[2][2];
695 double[][] array2 = new double[2][2];
704 final double[][] array1 = new double[2][2];
705 final double[][] array2 = new double[2][2];
696706 for (int i = 0; i < array1.length; ++i) {
697707 for (int j = 0; j < array1[0].length; j++) {
698708 array1[i][j] = (i + 1) * (j + 1);
707717
708718 @Test
709719 public void testMultiBooleanArray() {
710 boolean[][] array1 = new boolean[2][2];
711 boolean[][] array2 = new boolean[2][2];
720 final boolean[][] array1 = new boolean[2][2];
721 final boolean[][] array2 = new boolean[2][2];
712722 for (int i = 0; i < array1.length; ++i) {
713723 for (int j = 0; j < array1[0].length; j++) {
714724 array1[i][j] = i == 1 || j == 1;
721731 assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
722732
723733 // compare 1 dim to 2.
724 boolean[] array3 = new boolean[]{true, true};
734 final boolean[] array3 = new boolean[]{true, true};
725735 assertFalse(new EqualsBuilder().append(array1, array3).isEquals());
726736 assertFalse(new EqualsBuilder().append(array3, array1).isEquals());
727737 assertFalse(new EqualsBuilder().append(array2, array3).isEquals());
730740
731741 @Test
732742 public void testRaggedArray() {
733 long array1[][] = new long[2][];
734 long array2[][] = new long[2][];
743 final long array1[][] = new long[2][];
744 final long array2[][] = new long[2][];
735745 for (int i = 0; i < array1.length; ++i) {
736746 array1[i] = new long[2];
737747 array2[i] = new long[2];
748758
749759 @Test
750760 public void testMixedArray() {
751 Object array1[] = new Object[2];
752 Object array2[] = new Object[2];
761 final Object array1[] = new Object[2];
762 final Object array2[] = new Object[2];
753763 for (int i = 0; i < array1.length; ++i) {
754764 array1[i] = new long[2];
755765 array2[i] = new long[2];
766776
767777 @Test
768778 public void testObjectArrayHiddenByObject() {
769 TestObject[] array1 = new TestObject[2];
779 final TestObject[] array1 = new TestObject[2];
770780 array1[0] = new TestObject(4);
771781 array1[1] = new TestObject(5);
772 TestObject[] array2 = new TestObject[2];
782 final TestObject[] array2 = new TestObject[2];
773783 array2[0] = new TestObject(4);
774784 array2[1] = new TestObject(5);
775 Object obj1 = array1;
776 Object obj2 = array2;
785 final Object obj1 = array1;
786 final Object obj2 = array2;
777787 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
778788 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
779789 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
784794
785795 @Test
786796 public void testLongArrayHiddenByObject() {
787 long[] array1 = new long[2];
797 final long[] array1 = new long[2];
788798 array1[0] = 5L;
789799 array1[1] = 6L;
790 long[] array2 = new long[2];
800 final long[] array2 = new long[2];
791801 array2[0] = 5L;
792802 array2[1] = 6L;
793 Object obj1 = array1;
794 Object obj2 = array2;
803 final Object obj1 = array1;
804 final Object obj2 = array2;
795805 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
796806 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
797807 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
802812
803813 @Test
804814 public void testIntArrayHiddenByObject() {
805 int[] array1 = new int[2];
815 final int[] array1 = new int[2];
806816 array1[0] = 5;
807817 array1[1] = 6;
808 int[] array2 = new int[2];
818 final int[] array2 = new int[2];
809819 array2[0] = 5;
810820 array2[1] = 6;
811 Object obj1 = array1;
812 Object obj2 = array2;
821 final Object obj1 = array1;
822 final Object obj2 = array2;
813823 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
814824 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
815825 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
820830
821831 @Test
822832 public void testShortArrayHiddenByObject() {
823 short[] array1 = new short[2];
833 final short[] array1 = new short[2];
824834 array1[0] = 5;
825835 array1[1] = 6;
826 short[] array2 = new short[2];
836 final short[] array2 = new short[2];
827837 array2[0] = 5;
828838 array2[1] = 6;
829 Object obj1 = array1;
830 Object obj2 = array2;
839 final Object obj1 = array1;
840 final Object obj2 = array2;
831841 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
832842 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
833843 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
838848
839849 @Test
840850 public void testCharArrayHiddenByObject() {
841 char[] array1 = new char[2];
851 final char[] array1 = new char[2];
842852 array1[0] = 5;
843853 array1[1] = 6;
844 char[] array2 = new char[2];
854 final char[] array2 = new char[2];
845855 array2[0] = 5;
846856 array2[1] = 6;
847 Object obj1 = array1;
848 Object obj2 = array2;
857 final Object obj1 = array1;
858 final Object obj2 = array2;
849859 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
850860 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
851861 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
856866
857867 @Test
858868 public void testByteArrayHiddenByObject() {
859 byte[] array1 = new byte[2];
869 final byte[] array1 = new byte[2];
860870 array1[0] = 5;
861871 array1[1] = 6;
862 byte[] array2 = new byte[2];
872 final byte[] array2 = new byte[2];
863873 array2[0] = 5;
864874 array2[1] = 6;
865 Object obj1 = array1;
866 Object obj2 = array2;
875 final Object obj1 = array1;
876 final Object obj2 = array2;
867877 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
868878 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
869879 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
874884
875885 @Test
876886 public void testDoubleArrayHiddenByObject() {
877 double[] array1 = new double[2];
887 final double[] array1 = new double[2];
878888 array1[0] = 5;
879889 array1[1] = 6;
880 double[] array2 = new double[2];
890 final double[] array2 = new double[2];
881891 array2[0] = 5;
882892 array2[1] = 6;
883 Object obj1 = array1;
884 Object obj2 = array2;
893 final Object obj1 = array1;
894 final Object obj2 = array2;
885895 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
886896 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
887897 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
892902
893903 @Test
894904 public void testFloatArrayHiddenByObject() {
895 float[] array1 = new float[2];
905 final float[] array1 = new float[2];
896906 array1[0] = 5;
897907 array1[1] = 6;
898 float[] array2 = new float[2];
908 final float[] array2 = new float[2];
899909 array2[0] = 5;
900910 array2[1] = 6;
901 Object obj1 = array1;
902 Object obj2 = array2;
911 final Object obj1 = array1;
912 final Object obj2 = array2;
903913 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
904914 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
905915 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
910920
911921 @Test
912922 public void testBooleanArrayHiddenByObject() {
913 boolean[] array1 = new boolean[2];
923 final boolean[] array1 = new boolean[2];
914924 array1[0] = true;
915925 array1[1] = false;
916 boolean[] array2 = new boolean[2];
926 final boolean[] array2 = new boolean[2];
917927 array2[0] = true;
918928 array2[1] = false;
919 Object obj1 = array1;
920 Object obj2 = array2;
929 final Object obj1 = array1;
930 final Object obj2 = array2;
921931 assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals());
922932 assertTrue(new EqualsBuilder().append(obj1, array1).isEquals());
923933 assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
927937 }
928938
929939 public static class TestACanEqualB {
930 private int a;
931
932 public TestACanEqualB(int a) {
940 private final int a;
941
942 public TestACanEqualB(final int a) {
933943 this.a = a;
934944 }
935945
936946 @Override
937 public boolean equals(Object o) {
947 public boolean equals(final Object o) {
938948 if (o == this) {
939949 return true;
940950 }
947957 return false;
948958 }
949959
960 @Override
961 public int hashCode() {
962 return a;
963 }
964
950965 public int getA() {
951966 return this.a;
952967 }
953968 }
954969
955970 public static class TestBCanEqualA {
956 private int b;
957
958 public TestBCanEqualA(int b) {
971 private final int b;
972
973 public TestBCanEqualA(final int b) {
959974 this.b = b;
960975 }
961976
962977 @Override
963 public boolean equals(Object o) {
978 public boolean equals(final Object o) {
964979 if (o == this) {
965980 return true;
966981 }
971986 return this.b == ((TestBCanEqualA) o).getB();
972987 }
973988 return false;
989 }
990
991 @Override
992 public int hashCode() {
993 return b;
974994 }
975995
976996 public int getB() {
9851005 */
9861006 @Test
9871007 public void testUnrelatedClasses() {
988 Object[] x = new Object[]{new TestACanEqualB(1)};
989 Object[] y = new Object[]{new TestBCanEqualA(1)};
1008 final Object[] x = new Object[]{new TestACanEqualB(1)};
1009 final Object[] y = new Object[]{new TestBCanEqualA(1)};
9901010
9911011 // sanity checks:
9921012 assertTrue(Arrays.equals(x, x));
10091029 */
10101030 @Test
10111031 public void testNpeForNullElement() {
1012 Object[] x1 = new Object[] { Integer.valueOf(1), null, Integer.valueOf(3) };
1013 Object[] x2 = new Object[] { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3) };
1032 final Object[] x1 = new Object[] { Integer.valueOf(1), null, Integer.valueOf(3) };
1033 final Object[] x2 = new Object[] { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3) };
10141034
10151035 // causes an NPE in 2.0 according to:
10161036 // http://issues.apache.org/bugzilla/show_bug.cgi?id=33067
10191039
10201040 @Test
10211041 public void testReflectionEqualsExcludeFields() throws Exception {
1022 TestObjectWithMultipleFields x1 = new TestObjectWithMultipleFields(1, 2, 3);
1023 TestObjectWithMultipleFields x2 = new TestObjectWithMultipleFields(1, 3, 4);
1042 final TestObjectWithMultipleFields x1 = new TestObjectWithMultipleFields(1, 2, 3);
1043 final TestObjectWithMultipleFields x2 = new TestObjectWithMultipleFields(1, 3, 4);
10241044
10251045 // not equal when including all fields
10261046 assertTrue(!EqualsBuilder.reflectionEquals(x1, x2));
10441064
10451065 static class TestObjectWithMultipleFields {
10461066 @SuppressWarnings("unused")
1047 private TestObject one;
1067 private final TestObject one;
10481068 @SuppressWarnings("unused")
1049 private TestObject two;
1069 private final TestObject two;
10501070 @SuppressWarnings("unused")
1051 private TestObject three;
1052
1053 public TestObjectWithMultipleFields(int one, int two, int three) {
1071 private final TestObject three;
1072
1073 public TestObjectWithMultipleFields(final int one, final int two, final int three) {
10541074 this.one = new TestObject(one);
10551075 this.two = new TestObject(two);
10561076 this.three = new TestObject(three);
10631083 */
10641084 @Test
10651085 public void testCyclicalObjectReferences() {
1066 TestObjectReference refX1 = new TestObjectReference(1);
1067 TestObjectReference x1 = new TestObjectReference(1);
1086 final TestObjectReference refX1 = new TestObjectReference(1);
1087 final TestObjectReference x1 = new TestObjectReference(1);
10681088 x1.setObjectReference(refX1);
10691089 refX1.setObjectReference(x1);
10701090
1071 TestObjectReference refX2 = new TestObjectReference(1);
1072 TestObjectReference x2 = new TestObjectReference(1);
1091 final TestObjectReference refX2 = new TestObjectReference(1);
1092 final TestObjectReference x2 = new TestObjectReference(1);
10731093 x2.setObjectReference(refX2);
10741094 refX2.setObjectReference(x2);
10751095
1076 TestObjectReference refX3 = new TestObjectReference(2);
1077 TestObjectReference x3 = new TestObjectReference(2);
1096 final TestObjectReference refX3 = new TestObjectReference(2);
1097 final TestObjectReference x3 = new TestObjectReference(2);
10781098 x3.setObjectReference(refX3);
10791099 refX3.setObjectReference(x3);
10801100
10901110 @SuppressWarnings("unused")
10911111 private TestObjectReference reference;
10921112 @SuppressWarnings("unused")
1093 private TestObject one;
1094
1095 public TestObjectReference(int one) {
1113 private final TestObject one;
1114
1115 public TestObjectReference(final int one) {
10961116 this.one = new TestObject(one);
10971117 }
10981118
1099 public void setObjectReference(TestObjectReference reference) {
1119 public void setObjectReference(final TestObjectReference reference) {
11001120 this.reference = reference;
11011121 }
11021122
11031123 @Override
1104 public boolean equals(Object obj) {
1124 public boolean equals(final Object obj) {
11051125 return EqualsBuilder.reflectionEquals(this, obj);
11061126 }
11071127 }
1128
1129 @Test
1130 public void testReflectionArrays() throws Exception {
1131
1132 final TestObject one = new TestObject(1);
1133 final TestObject two = new TestObject(2);
1134
1135 Object[] o1 = new Object[] { one };
1136 Object[] o2 = new Object[] { two };
1137 Object[] o3 = new Object[] { one };
1138
1139 assertTrue(!EqualsBuilder.reflectionEquals(o1, o2));
1140 assertTrue(EqualsBuilder.reflectionEquals(o1, o1));
1141 assertTrue(EqualsBuilder.reflectionEquals(o1, o3));
1142
1143 double[] d1 = { 0, 1 };
1144 double[] d2 = { 2, 3 };
1145 double[] d3 = { 0, 1 };
1146
1147 assertTrue(!EqualsBuilder.reflectionEquals(d1, d2));
1148 assertTrue(EqualsBuilder.reflectionEquals(d1, d1));
1149 assertTrue(EqualsBuilder.reflectionEquals(d1, d3));
1150 }
1151
11081152 }
11091153
2424 * {@link org.apache.commons.lang3.builder.EqualsBuilderTest} to insure that equal
2525 * objects must have equal hash codes.
2626 *
27 * @version $Id: HashCodeBuilderAndEqualsBuilderTest.java 1185707 2011-10-18 15:01:49Z ggregory $
27 * @version $Id: HashCodeBuilderAndEqualsBuilderTest.java 1544776 2013-11-23 12:25:48Z sebb $
2828 */
2929 public class HashCodeBuilderAndEqualsBuilderTest {
3030
3131 //-----------------------------------------------------------------------
3232
33 private void testInteger(boolean testTransients) {
34 Integer i1 = Integer.valueOf(12345);
35 Integer i2 = Integer.valueOf(12345);
33 private void testInteger(final boolean testTransients) {
34 final Integer i1 = Integer.valueOf(12345);
35 final Integer i2 = Integer.valueOf(12345);
3636 assertEqualsAndHashCodeContract(i1, i2, testTransients);
3737 }
3838
5656 testFixture(true);
5757 }
5858
59 private void testFixture(boolean testTransients) {
59 private void testFixture(final boolean testTransients) {
6060 assertEqualsAndHashCodeContract(new TestFixture(2, 'c', "Test", (short) 2), new TestFixture(2, 'c', "Test", (short) 2), testTransients);
6161 assertEqualsAndHashCodeContract(
6262 new AllTransientFixture(2, 'c', "Test", (short) 2),
7878 *
7979 * @param lhs The Left-Hand-Side of the equals test
8080 * @param rhs The Right-Hand-Side of the equals test
81 * @param testTransients wether to test transient fields
81 * @param testTransients whether to test transient fields
8282 */
83 private void assertEqualsAndHashCodeContract(Object lhs, Object rhs, boolean testTransients) {
83 private void assertEqualsAndHashCodeContract(final Object lhs, final Object rhs, final boolean testTransients) {
8484 if (EqualsBuilder.reflectionEquals(lhs, rhs, testTransients)) {
8585 // test a couple of times for consistency.
8686 assertEquals(HashCodeBuilder.reflectionHashCode(lhs, testTransients), HashCodeBuilder.reflectionHashCode(rhs, testTransients));
9595 String string;
9696 short s;
9797
98 TestFixture(int i, char c, String string, short s) {
98 TestFixture(final int i, final char c, final String string, final short s) {
9999 this.i = i;
100100 this.c = c;
101101 this.string = string;
106106 static class SubTestFixture extends TestFixture {
107107 transient String tString;
108108
109 SubTestFixture(int i, char c, String string, short s, String tString) {
109 SubTestFixture(final int i, final char c, final String string, final short s, final String tString) {
110110 super(i, c, string, s);
111111 this.tString = tString;
112112 }
118118 transient String string;
119119 transient short s;
120120
121 AllTransientFixture(int i, char c, String string, short s) {
121 AllTransientFixture(final int i, final char c, final String string, final short s) {
122122 this.i = i;
123123 this.c = c;
124124 this.string = string;
129129 static class SubAllTransientFixture extends AllTransientFixture {
130130 transient String tString;
131131
132 SubAllTransientFixture(int i, char c, String string, short s, String tString) {
132 SubAllTransientFixture(final int i, final char c, final String string, final short s, final String tString) {
133133 super(i, c, string, s);
134134 this.tString = tString;
135135 }
1818
1919 import static org.junit.Assert.assertEquals;
2020 import static org.junit.Assert.assertNull;
21 import static org.junit.Assert.fail;
22
2321 import org.junit.Test;
2422
2523 /**
2624 * Unit tests {@link org.apache.commons.lang3.builder.HashCodeBuilder}.
2725 *
28 * @version $Id: HashCodeBuilderTest.java 1199894 2011-11-09 17:53:59Z ggregory $
26 * @version $Id: HashCodeBuilderTest.java 1526817 2013-09-27 07:49:02Z britter $
2927 */
3028 public class HashCodeBuilderTest {
3129
5553
5654 // -----------------------------------------------------------------------
5755
58 @Test
59 public void testConstructorEx1() {
60 try {
61 new HashCodeBuilder(0, 0);
62
63 } catch (IllegalArgumentException ex) {
64 return;
65 }
66 fail();
67 }
68
69 @Test
70 public void testConstructorEx2() {
71 try {
72 new HashCodeBuilder(2, 2);
73
74 } catch (IllegalArgumentException ex) {
75 return;
76 }
77 fail();
56 @Test(expected=IllegalArgumentException.class)
57 public void testConstructorExZero() {
58 new HashCodeBuilder(0, 0);
59 }
60
61 @Test(expected=IllegalArgumentException.class)
62 public void testConstructorExEven() {
63 new HashCodeBuilder(2, 2);
64 }
65
66 @Test(expected=IllegalArgumentException.class)
67 public void testConstructorExEvenNegative() {
68 new HashCodeBuilder(-2, -2);
7869 }
7970
8071 static class TestObject {
8172 private int a;
8273
83 public TestObject(int a) {
74 public TestObject(final int a) {
8475 this.a = a;
8576 }
8677
8778 @Override
88 public boolean equals(Object o) {
79 public boolean equals(final Object o) {
8980 if (o == this) {
9081 return true;
9182 }
9283 if (!(o instanceof TestObject)) {
9384 return false;
9485 }
95 TestObject rhs = (TestObject) o;
86 final TestObject rhs = (TestObject) o;
9687 return a == rhs.a;
9788 }
9889
99 public void setA(int a) {
90 @Override
91 public int hashCode() {
92 return a;
93 }
94
95 public void setA(final int a) {
10096 this.a = a;
10197 }
10298
115111 super(0);
116112 }
117113
118 public TestSubObject(int a, int b, int t) {
114 public TestSubObject(final int a, final int b, final int t) {
119115 super(a);
120116 this.b = b;
121117 this.t = t;
122118 }
123119
124120 @Override
125 public boolean equals(Object o) {
121 public boolean equals(final Object o) {
126122 if (o == this) {
127123 return true;
128124 }
129125 if (!(o instanceof TestSubObject)) {
130126 return false;
131127 }
132 TestSubObject rhs = (TestSubObject) o;
128 final TestSubObject rhs = (TestSubObject) o;
133129 return super.equals(o) && b == rhs.b;
134130 }
131
132 @Override
133 public int hashCode() {
134 return b*17 + super.hashCode();
135 }
136
135137 }
136138
137139 @Test
150152 123456, 7890, 0), true));
151153 }
152154
153 @Test
155 @Test(expected=IllegalArgumentException.class)
154156 public void testReflectionHierarchyHashCodeEx1() {
155 try {
156 HashCodeBuilder.reflectionHashCode(0, 0, new TestSubObject(0, 0, 0), true);
157 } catch (IllegalArgumentException ex) {
158 return;
159 }
160 fail();
161 }
162
163 @Test
157 HashCodeBuilder.reflectionHashCode(0, 0, new TestSubObject(0, 0, 0), true);
158 }
159
160 @Test(expected=IllegalArgumentException.class)
164161 public void testReflectionHierarchyHashCodeEx2() {
165 try {
166 HashCodeBuilder.reflectionHashCode(2, 2, new TestSubObject(0, 0, 0), true);
167 } catch (IllegalArgumentException ex) {
168 return;
169 }
170 fail();
171 }
172
173 @Test
162 HashCodeBuilder.reflectionHashCode(2, 2, new TestSubObject(0, 0, 0), true);
163 }
164
165 @Test(expected=IllegalArgumentException.class)
174166 public void testReflectionHashCodeEx1() {
175 try {
176 HashCodeBuilder.reflectionHashCode(0, 0, new TestObject(0), true);
177 } catch (IllegalArgumentException ex) {
178 return;
179 }
180 fail();
181 }
182
183 @Test
167 HashCodeBuilder.reflectionHashCode(0, 0, new TestObject(0), true);
168 }
169
170 @Test(expected=IllegalArgumentException.class)
184171 public void testReflectionHashCodeEx2() {
185 try {
186 HashCodeBuilder.reflectionHashCode(2, 2, new TestObject(0), true);
187 } catch (IllegalArgumentException ex) {
188 return;
189 }
190 fail();
191 }
192
193 @Test
172 HashCodeBuilder.reflectionHashCode(2, 2, new TestObject(0), true);
173 }
174
175 @Test(expected=IllegalArgumentException.class)
194176 public void testReflectionHashCodeEx3() {
195 try {
196 HashCodeBuilder.reflectionHashCode(13, 19, null, true);
197 } catch (IllegalArgumentException ex) {
198 return;
199 }
200 fail();
177 HashCodeBuilder.reflectionHashCode(13, 19, null, true);
201178 }
202179
203180 @Test
204181 public void testSuper() {
205 Object obj = new Object();
182 final Object obj = new Object();
206183 assertEquals(17 * 37 + 19 * 41 + obj.hashCode(), new HashCodeBuilder(17, 37).appendSuper(
207184 new HashCodeBuilder(19, 41).append(obj).toHashCode()).toHashCode());
208185 }
260237 @SuppressWarnings("cast") // cast is not really needed, keep for consistency
261238 public void testDouble() {
262239 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((double) 0d).toHashCode());
263 double d = 1234567.89;
264 long l = Double.doubleToLongBits(d);
240 final double d = 1234567.89;
241 final long l = Double.doubleToLongBits(d);
265242 assertEquals(17 * 37 + (int) (l ^ l >> 32), new HashCodeBuilder(17, 37).append(d).toHashCode());
266243 }
267244
269246 @SuppressWarnings("cast") // cast is not really needed, keep for consistency
270247 public void testFloat() {
271248 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((float) 0f).toHashCode());
272 float f = 1234.89f;
273 int i = Float.floatToIntBits(f);
249 final float f = 1234.89f;
250 final int i = Float.floatToIntBits(f);
274251 assertEquals(17 * 37 + i, new HashCodeBuilder(17, 37).append(f).toHashCode());
275252 }
276253
283260 @Test
284261 public void testObjectArray() {
285262 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((Object[]) null).toHashCode());
286 Object[] obj = new Object[2];
263 final Object[] obj = new Object[2];
287264 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
288265 obj[0] = new Object();
289266 assertEquals((17 * 37 + obj[0].hashCode()) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
294271
295272 @Test
296273 public void testObjectArrayAsObject() {
297 Object[] obj = new Object[2];
274 final Object[] obj = new Object[2];
298275 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
299276 obj[0] = new Object();
300277 assertEquals((17 * 37 + obj[0].hashCode()) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
306283 @Test
307284 public void testLongArray() {
308285 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((long[]) null).toHashCode());
309 long[] obj = new long[2];
286 final long[] obj = new long[2];
310287 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
311288 obj[0] = 5L;
312 int h1 = (int) (5L ^ 5L >> 32);
289 final int h1 = (int) (5L ^ 5L >> 32);
313290 assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
314291 obj[1] = 6L;
315 int h2 = (int) (6L ^ 6L >> 32);
292 final int h2 = (int) (6L ^ 6L >> 32);
316293 assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode());
317294 }
318295
319296 @Test
320297 public void testLongArrayAsObject() {
321 long[] obj = new long[2];
298 final long[] obj = new long[2];
322299 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
323300 obj[0] = 5L;
324 int h1 = (int) (5L ^ 5L >> 32);
301 final int h1 = (int) (5L ^ 5L >> 32);
325302 assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
326303 obj[1] = 6L;
327 int h2 = (int) (6L ^ 6L >> 32);
304 final int h2 = (int) (6L ^ 6L >> 32);
328305 assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
329306 }
330307
331308 @Test
332309 public void testIntArray() {
333310 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((int[]) null).toHashCode());
334 int[] obj = new int[2];
311 final int[] obj = new int[2];
335312 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
336313 obj[0] = 5;
337314 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
341318
342319 @Test
343320 public void testIntArrayAsObject() {
344 int[] obj = new int[2];
321 final int[] obj = new int[2];
345322 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
346323 obj[0] = 5;
347324 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
352329 @Test
353330 public void testShortArray() {
354331 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((short[]) null).toHashCode());
355 short[] obj = new short[2];
332 final short[] obj = new short[2];
356333 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
357334 obj[0] = (short) 5;
358335 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
362339
363340 @Test
364341 public void testShortArrayAsObject() {
365 short[] obj = new short[2];
342 final short[] obj = new short[2];
366343 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
367344 obj[0] = (short) 5;
368345 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
373350 @Test
374351 public void testCharArray() {
375352 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((char[]) null).toHashCode());
376 char[] obj = new char[2];
353 final char[] obj = new char[2];
377354 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
378355 obj[0] = (char) 5;
379356 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
383360
384361 @Test
385362 public void testCharArrayAsObject() {
386 char[] obj = new char[2];
363 final char[] obj = new char[2];
387364 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
388365 obj[0] = (char) 5;
389366 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
394371 @Test
395372 public void testByteArray() {
396373 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((byte[]) null).toHashCode());
397 byte[] obj = new byte[2];
374 final byte[] obj = new byte[2];
398375 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
399376 obj[0] = (byte) 5;
400377 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
404381
405382 @Test
406383 public void testByteArrayAsObject() {
407 byte[] obj = new byte[2];
384 final byte[] obj = new byte[2];
408385 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
409386 obj[0] = (byte) 5;
410387 assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
415392 @Test
416393 public void testDoubleArray() {
417394 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((double[]) null).toHashCode());
418 double[] obj = new double[2];
395 final double[] obj = new double[2];
419396 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
420397 obj[0] = 5.4d;
421 long l1 = Double.doubleToLongBits(5.4d);
422 int h1 = (int) (l1 ^ l1 >> 32);
398 final long l1 = Double.doubleToLongBits(5.4d);
399 final int h1 = (int) (l1 ^ l1 >> 32);
423400 assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
424401 obj[1] = 6.3d;
425 long l2 = Double.doubleToLongBits(6.3d);
426 int h2 = (int) (l2 ^ l2 >> 32);
402 final long l2 = Double.doubleToLongBits(6.3d);
403 final int h2 = (int) (l2 ^ l2 >> 32);
427404 assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode());
428405 }
429406
430407 @Test
431408 public void testDoubleArrayAsObject() {
432 double[] obj = new double[2];
409 final double[] obj = new double[2];
433410 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
434411 obj[0] = 5.4d;
435 long l1 = Double.doubleToLongBits(5.4d);
436 int h1 = (int) (l1 ^ l1 >> 32);
412 final long l1 = Double.doubleToLongBits(5.4d);
413 final int h1 = (int) (l1 ^ l1 >> 32);
437414 assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
438415 obj[1] = 6.3d;
439 long l2 = Double.doubleToLongBits(6.3d);
440 int h2 = (int) (l2 ^ l2 >> 32);
416 final long l2 = Double.doubleToLongBits(6.3d);
417 final int h2 = (int) (l2 ^ l2 >> 32);
441418 assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
442419 }
443420
444421 @Test
445422 public void testFloatArray() {
446423 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((float[]) null).toHashCode());
447 float[] obj = new float[2];
424 final float[] obj = new float[2];
448425 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
449426 obj[0] = 5.4f;
450 int h1 = Float.floatToIntBits(5.4f);
427 final int h1 = Float.floatToIntBits(5.4f);
451428 assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
452429 obj[1] = 6.3f;
453 int h2 = Float.floatToIntBits(6.3f);
430 final int h2 = Float.floatToIntBits(6.3f);
454431 assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode());
455432 }
456433
457434 @Test
458435 public void testFloatArrayAsObject() {
459 float[] obj = new float[2];
436 final float[] obj = new float[2];
460437 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
461438 obj[0] = 5.4f;
462 int h1 = Float.floatToIntBits(5.4f);
439 final int h1 = Float.floatToIntBits(5.4f);
463440 assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
464441 obj[1] = 6.3f;
465 int h2 = Float.floatToIntBits(6.3f);
442 final int h2 = Float.floatToIntBits(6.3f);
466443 assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
467444 }
468445
469446 @Test
470447 public void testBooleanArray() {
471448 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((boolean[]) null).toHashCode());
472 boolean[] obj = new boolean[2];
449 final boolean[] obj = new boolean[2];
473450 assertEquals((17 * 37 + 1) * 37 + 1, new HashCodeBuilder(17, 37).append(obj).toHashCode());
474451 obj[0] = true;
475452 assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append(obj).toHashCode());
479456
480457 @Test
481458 public void testBooleanArrayAsObject() {
482 boolean[] obj = new boolean[2];
459 final boolean[] obj = new boolean[2];
483460 assertEquals((17 * 37 + 1) * 37 + 1, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
484461 obj[0] = true;
485462 assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
489466
490467 @Test
491468 public void testBooleanMultiArray() {
492 boolean[][] obj = new boolean[2][];
469 final boolean[][] obj = new boolean[2][];
493470 assertEquals(17 * 37 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
494471 obj[0] = new boolean[0];
495472 assertEquals(17 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
505482
506483 @Test
507484 public void testReflectionHashCodeExcludeFields() throws Exception {
508 TestObjectWithMultipleFields x = new TestObjectWithMultipleFields(1, 2, 3);
485 final TestObjectWithMultipleFields x = new TestObjectWithMultipleFields(1, 2, 3);
509486
510487 assertEquals(((17 * 37 + 1) * 37 + 2) * 37 + 3, HashCodeBuilder.reflectionHashCode(x));
511488
532509 @SuppressWarnings("unused")
533510 private int three = 0;
534511
535 public TestObjectWithMultipleFields(int one, int two, int three) {
512 public TestObjectWithMultipleFields(final int one, final int two, final int three) {
536513 this.one = one;
537514 this.two = two;
538515 this.three = three;
544521 */
545522 @Test
546523 public void testReflectionObjectCycle() {
547 ReflectionTestCycleA a = new ReflectionTestCycleA();
548 ReflectionTestCycleB b = new ReflectionTestCycleB();
524 final ReflectionTestCycleA a = new ReflectionTestCycleA();
525 final ReflectionTestCycleB b = new ReflectionTestCycleB();
549526 a.b = b;
550527 b.a = a;
551528
577554 */
578555 @Test
579556 public void testToHashCodeEqualsHashCode() {
580 HashCodeBuilder hcb = new HashCodeBuilder(17, 37).append(new Object()).append('a');
557 final HashCodeBuilder hcb = new HashCodeBuilder(17, 37).append(new Object()).append('a');
581558 assertEquals("hashCode() is no longer returning the same value as toHashCode() - see LANG-520",
582559 hcb.toHashCode(), hcb.hashCode());
583560 }
2929 /**
3030 * Unit tests {@link org.apache.commons.lang3.builder.MultiLineToStringStyleTest}.
3131 *
32 * @version $Id: MultiLineToStringStyleTest.java 1185704 2011-10-18 14:56:56Z ggregory $
32 * @version $Id: MultiLineToStringStyleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3333 */
3434 public class MultiLineToStringStyleTest {
3535
6565
6666 @Test
6767 public void testObject() {
68 Integer i3 = Integer.valueOf(3);
69 Integer i4 = Integer.valueOf(4);
68 final Integer i3 = Integer.valueOf(3);
69 final Integer i4 = Integer.valueOf(4);
7070 assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " <null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) null).toString());
7171 assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " 3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(i3).toString());
7272 assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=<null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) null).toString());
8383
8484 @Test
8585 public void testPerson() {
86 Person p = new Person();
86 final Person p = new Person();
8787 p.name = "Jane Doe";
8888 p.age = 25;
8989 p.smoker = true;
90 String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p));
90 final String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p));
9191 assertEquals(pBaseStr + "[" + SystemUtils.LINE_SEPARATOR + " name=Jane Doe" + SystemUtils.LINE_SEPARATOR + " age=25" + SystemUtils.LINE_SEPARATOR + " smoker=true" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString());
9292 }
9393
2828 /**
2929 * Unit tests {@link org.apache.commons.lang3.builder.NoFieldNamesToStringStyleTest}.
3030 *
31 * @version $Id: NoFieldNamesToStringStyleTest.java 1185703 2011-10-18 14:55:38Z ggregory $
31 * @version $Id: NoFieldNamesToStringStyleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3232 */
3333 public class NoFieldNamesToStringStyleTest {
3434
6464
6565 @Test
6666 public void testObject() {
67 Integer i3 = Integer.valueOf(3);
68 Integer i4 = Integer.valueOf(4);
67 final Integer i3 = Integer.valueOf(3);
68 final Integer i4 = Integer.valueOf(4);
6969 assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).toString());
7070 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString());
7171 assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append("a", (Object) null).toString());
8282
8383 @Test
8484 public void testPerson() {
85 Person p = new Person();
85 final Person p = new Person();
8686 p.name = "Ron Paul";
8787 p.age = 72;
8888 p.smoker = false;
89 String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p));
89 final String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p));
9090 assertEquals(pBaseStr + "[Ron Paul,72,false]", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString());
9191 }
9292
2727 import java.util.concurrent.Executors;
2828 import java.util.concurrent.Future;
2929
30 import junit.framework.Assert;
30 import org.junit.Assert;
3131
3232 import org.junit.Ignore;
3333 import org.junit.Test;
4545 * @see <a href="https://issues.apache.org/jira/browse/LANG-762">[LANG-762] Handle or document ReflectionToStringBuilder
4646 * and ToStringBuilder for collections that are not thread safe</a>
4747 * @since 3.1
48 * @version $Id: ReflectionToStringBuilderConcurrencyTest.java 1200096 2011-11-10 02:07:43Z ggregory $
48 * @version $Id: ReflectionToStringBuilderConcurrencyTest.java 1437526 2013-01-23 16:05:20Z ggregory $
4949 */
5050 public class ReflectionToStringBuilderConcurrencyTest {
5151
5252 static class CollectionHolder<T extends Collection<?>> {
5353 T collection;
5454
55 CollectionHolder(T collection) {
55 CollectionHolder(final T collection) {
5656 this.collection = collection;
5757 }
5858 }
8888 // Create a thread pool with two threads to cause the most contention on the underlying resource.
8989 final ExecutorService threadPool = Executors.newFixedThreadPool(2);
9090 // Consumes toStrings
91 Callable<Integer> consumer = new Callable<Integer>() {
91 final Callable<Integer> consumer = new Callable<Integer>() {
92 @Override
9293 public Integer call() {
9394 for (int i = 0; i < REPEAT; i++) {
94 String s = ReflectionToStringBuilder.toString(holder);
95 final String s = ReflectionToStringBuilder.toString(holder);
9596 Assert.assertNotNull(s);
9697 }
97 return REPEAT;
98 return Integer.valueOf(REPEAT);
9899 }
99100 };
100101 // Produces changes in the list
101 Callable<Integer> producer = new Callable<Integer>() {
102 final Callable<Integer> producer = new Callable<Integer>() {
103 @Override
102104 public Integer call() {
103105 for (int i = 0; i < DATA_SIZE; i++) {
104106 list.remove(list.get(0));
105107 }
106 return REPEAT;
108 return Integer.valueOf(REPEAT);
107109 }
108110 };
109 Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
111 final Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
110112 tasks.add(consumer);
111113 tasks.add(producer);
112114 final List<Future<Integer>> futures = threadPool.invokeAll(tasks);
113 for (Future<Integer> future : futures) {
115 for (final Future<Integer> future : futures) {
114116 Assert.assertEquals(REPEAT, future.get().intValue());
115117 }
116118 }
2020 import java.util.Collection;
2121 import java.util.List;
2222
23 import junit.framework.Assert;
23 import org.junit.Assert;
2424
2525 import org.apache.commons.lang3.ArrayUtils;
2626 import org.junit.Test;
2727
2828 /**
29 * @version $Id: ReflectionToStringBuilderExcludeTest.java 1185702 2011-10-18 14:53:59Z ggregory $
29 * @version $Id: ReflectionToStringBuilderExcludeTest.java 1437526 2013-01-23 16:05:20Z ggregory $
3030 */
3131 public class ReflectionToStringBuilderExcludeTest {
3232
3333 class TestFixture {
3434 @SuppressWarnings("unused")
35 private String secretField = SECRET_VALUE;
35 private final String secretField = SECRET_VALUE;
3636
3737 @SuppressWarnings("unused")
38 private String showField = NOT_SECRET_VALUE;
38 private final String showField = NOT_SECRET_VALUE;
3939 }
4040
4141 private static final String NOT_SECRET_FIELD = "showField";
4848
4949 @Test
5050 public void test_toStringExclude() {
51 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), SECRET_FIELD);
51 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), SECRET_FIELD);
5252 this.validateSecretFieldAbsent(toString);
5353 }
5454
5555 @Test
5656 public void test_toStringExcludeArray() {
57 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{SECRET_FIELD});
57 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{SECRET_FIELD});
5858 this.validateSecretFieldAbsent(toString);
5959 }
6060
6161 @Test
6262 public void test_toStringExcludeArrayWithNull() {
63 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{null});
63 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{null});
6464 this.validateSecretFieldPresent(toString);
6565 }
6666
6767 @Test
6868 public void test_toStringExcludeArrayWithNulls() {
69 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{null, null});
69 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{null, null});
7070 this.validateSecretFieldPresent(toString);
7171 }
7272
7373 @Test
7474 public void test_toStringExcludeCollection() {
75 List<String> excludeList = new ArrayList<String>();
75 final List<String> excludeList = new ArrayList<String>();
7676 excludeList.add(SECRET_FIELD);
77 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList);
77 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList);
7878 this.validateSecretFieldAbsent(toString);
7979 }
8080
8181 @Test
8282 public void test_toStringExcludeCollectionWithNull() {
83 List<String> excludeList = new ArrayList<String>();
83 final List<String> excludeList = new ArrayList<String>();
8484 excludeList.add(null);
85 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList);
85 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList);
8686 this.validateSecretFieldPresent(toString);
8787 }
8888
8989 @Test
9090 public void test_toStringExcludeCollectionWithNulls() {
91 List<String> excludeList = new ArrayList<String>();
91 final List<String> excludeList = new ArrayList<String>();
9292 excludeList.add(null);
9393 excludeList.add(null);
94 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList);
94 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList);
9595 this.validateSecretFieldPresent(toString);
9696 }
9797
9898 @Test
9999 public void test_toStringExcludeEmptyArray() {
100 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), ArrayUtils.EMPTY_STRING_ARRAY);
100 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), ArrayUtils.EMPTY_STRING_ARRAY);
101101 this.validateSecretFieldPresent(toString);
102102 }
103103
104104 @Test
105105 public void test_toStringExcludeEmptyCollection() {
106 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new ArrayList<String>());
106 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new ArrayList<String>());
107107 this.validateSecretFieldPresent(toString);
108108 }
109109
110110 @Test
111111 public void test_toStringExcludeNullArray() {
112 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), (String[]) null);
112 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), (String[]) null);
113113 this.validateSecretFieldPresent(toString);
114114 }
115115
116116 @Test
117117 public void test_toStringExcludeNullCollection() {
118 String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), (Collection<String>) null);
118 final String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), (Collection<String>) null);
119119 this.validateSecretFieldPresent(toString);
120120 }
121121
122 private void validateNonSecretField(String toString) {
122 private void validateNonSecretField(final String toString) {
123123 Assert.assertTrue(toString.indexOf(NOT_SECRET_FIELD) > ArrayUtils.INDEX_NOT_FOUND);
124124 Assert.assertTrue(toString.indexOf(NOT_SECRET_VALUE) > ArrayUtils.INDEX_NOT_FOUND);
125125 }
126126
127 private void validateSecretFieldAbsent(String toString) {
127 private void validateSecretFieldAbsent(final String toString) {
128128 Assert.assertEquals(ArrayUtils.INDEX_NOT_FOUND, toString.indexOf(SECRET_VALUE));
129129 this.validateNonSecretField(toString);
130130 }
131131
132 private void validateSecretFieldPresent(String toString) {
132 private void validateSecretFieldPresent(final String toString) {
133133 Assert.assertTrue(toString.indexOf(SECRET_VALUE) > 0);
134134 this.validateNonSecretField(toString);
135135 }
3939 class TestFixture {
4040 final private LinkedList<Integer> listField = new LinkedList<Integer>();
4141 final private Random random = new Random();
42 private int N = 100;
42 private final int N = 100;
4343
4444 public TestFixture() {
4545 synchronized (this) {
6262 final private TestFixture testFixture;
6363 final private Random random = new Random();
6464
65 public MutatingClient(TestFixture testFixture) {
65 public MutatingClient(final TestFixture testFixture) {
6666 this.testFixture = testFixture;
6767 }
6868
69 @Override
6970 public void run() {
7071 if (random.nextBoolean()) {
7172 testFixture.add();
7778
7879 class InspectingClient implements Runnable {
7980 final private TestFixture testFixture;
80 final private Random random = new Random();
8181
82 public InspectingClient(TestFixture testFixture) {
82 public InspectingClient(final TestFixture testFixture) {
8383 this.testFixture = testFixture;
8484 }
8585
86 @Override
8687 public void run() {
8788 ReflectionToStringBuilder.toString(testFixture);
8889 }
9192 @Test
9293 @Ignore
9394 public void testConcurrency() throws Exception {
94 TestFixture testFixture = new TestFixture();
95 final TestFixture testFixture = new TestFixture();
9596 final int numMutators = 10;
9697 final int numIterations = 10;
9798 for (int i = 0; i < numIterations; i++) {
9899 for (int j = 0; j < numMutators; j++) {
99 Thread t = new Thread(new MutatingClient(testFixture));
100 final Thread t = new Thread(new MutatingClient(testFixture));
100101 t.start();
101 Thread s = new Thread(new InspectingClient(testFixture));
102 final Thread s = new Thread(new InspectingClient(testFixture));
102103 s.start();
103104 }
104105 }
2828 /**
2929 * Unit tests {@link org.apache.commons.lang3.builder.ToStringStyle#SHORT_PREFIX_STYLE}.
3030 *
31 * @version $Id: ShortPrefixToStringStyleTest.java 1185700 2011-10-18 14:52:55Z ggregory $
31 * @version $Id: ShortPrefixToStringStyleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3232 */
3333 public class ShortPrefixToStringStyleTest {
3434
6464
6565 @Test
6666 public void testObject() {
67 Integer i3 = Integer.valueOf(3);
68 Integer i4 = Integer.valueOf(4);
67 final Integer i3 = Integer.valueOf(3);
68 final Integer i4 = Integer.valueOf(4);
6969 assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).toString());
7070 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString());
7171 assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).toString());
8282
8383 @Test
8484 public void testPerson() {
85 Person p = new Person();
85 final Person p = new Person();
8686 p.name = "John Q. Public";
8787 p.age = 45;
8888 p.smoker = true;
89 String pBaseStr = "ToStringStyleTest.Person";
89 final String pBaseStr = "ToStringStyleTest.Person";
9090 assertEquals(pBaseStr + "[name=John Q. Public,age=45,smoker=true]", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString());
9191 }
9292
2828 /**
2929 * Unit tests {@link org.apache.commons.lang3.builder.SimpleToStringStyleTest}.
3030 *
31 * @version $Id: SimpleToStringStyleTest.java 1185699 2011-10-18 14:51:31Z ggregory $
31 * @version $Id: SimpleToStringStyleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3232 */
3333 public class SimpleToStringStyleTest {
3434
6363
6464 @Test
6565 public void testObject() {
66 Integer i3 = Integer.valueOf(3);
67 Integer i4 = Integer.valueOf(4);
66 final Integer i3 = Integer.valueOf(3);
67 final Integer i4 = Integer.valueOf(4);
6868 assertEquals("<null>", new ToStringBuilder(base).append((Object) null).toString());
6969 assertEquals("3", new ToStringBuilder(base).append(i3).toString());
7070 assertEquals("<null>", new ToStringBuilder(base).append("a", (Object) null).toString());
8181
8282 @Test
8383 public void testPerson() {
84 Person p = new Person();
84 final Person p = new Person();
8585 p.name = "Jane Q. Public";
8686 p.age = 47;
8787 p.smoker = false;
2828 /**
2929 * Unit tests {@link org.apache.commons.lang3.builder.ToStringStyle}.
3030 *
31 * @version $Id: StandardToStringStyleTest.java 1185697 2011-10-18 14:50:15Z ggregory $
31 * @version $Id: StandardToStringStyleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3232 */
3333 public class StandardToStringStyleTest {
3434
7979
8080 @Test
8181 public void testObject() {
82 Integer i3 = Integer.valueOf(3);
83 Integer i4 = Integer.valueOf(4);
82 final Integer i3 = Integer.valueOf(3);
83 final Integer i4 = Integer.valueOf(4);
8484 assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append((Object) null).toString());
8585 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString());
8686 assertEquals(baseStr + "[a=%NULL%]", new ToStringBuilder(base).append("a", (Object) null).toString());
9797
9898 @Test
9999 public void testPerson() {
100 Person p = new Person();
100 final Person p = new Person();
101101 p.name = "Suzy Queue";
102102 p.age = 19;
103103 p.smoker = false;
104 String pBaseStr = "ToStringStyleTest.Person";
104 final String pBaseStr = "ToStringStyleTest.Person";
105105 assertEquals(pBaseStr + "[name=Suzy Queue,age=19,smoker=false]", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString());
106106 }
107107
1515 */
1616 package org.apache.commons.lang3.builder;
1717
18 import static org.junit.Assert.*;
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertNull;
20 import static org.junit.Assert.assertSame;
21 import static org.junit.Assume.assumeFalse;
1922
2023 import java.util.ArrayList;
2124 import java.util.HashMap;
2225 import java.util.List;
23
26 import java.util.Map;
27
28 import org.apache.commons.lang3.SystemUtils;
29 import org.junit.After;
2430 import org.junit.Test;
25
26 import org.apache.commons.lang3.SystemUtils;
2731
2832 /**
2933 * Unit tests for {@link org.apache.commons.lang3.builder.ToStringBuilder}.
3034 *
31 * @version $Id: ToStringBuilderTest.java 1154530 2011-08-06 15:43:07Z joehni $
35 * @version $Id: ToStringBuilderTest.java 1533566 2013-10-18 17:21:23Z sebb $
3236 */
3337 public class ToStringBuilderTest {
3438
3539 private final Integer base = Integer.valueOf(5);
3640 private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base));
41
42 /*
43 * All tests should leave the registry empty.
44 */
45 @After
46 public void after(){
47 validateNullToStringStyleRegistry();
48 }
3749
3850 //-----------------------------------------------------------------------
3951
5163 @Test
5264 public void testConstructorEx3() {
5365 assertEquals("<null>", new ToStringBuilder(null, null, null).toString());
54 new ToStringBuilder(this.base, null, null);
55 new ToStringBuilder(this.base, ToStringStyle.DEFAULT_STYLE, null);
66 new ToStringBuilder(this.base, null, null).toString();
67 new ToStringBuilder(this.base, ToStringStyle.DEFAULT_STYLE, null).toString();
5668 }
5769
5870 @Test
6678 }
6779 }
6880
69 @Test
81 @Test(expected=IllegalArgumentException.class)
7082 public void testSetDefaultEx() {
71 try {
72 ToStringBuilder.setDefaultStyle(null);
73
74 } catch (IllegalArgumentException ex) {
75 return;
76 }
77 fail();
83 ToStringBuilder.setDefaultStyle(null);
7884 }
7985
8086 @Test
95101 */
96102 @Test
97103 public void testReflectionCharacter() {
98 Character c = new Character('A');
104 final Character c = new Character('A');
99105 assertEquals(this.toBaseString(c) + "[value=A]", ToStringBuilder.reflectionToString(c));
100106 }
101107
116122 * @param o the object to create the string for.
117123 * @return a String in the Object.toString format.
118124 */
119 private String toBaseString(Object o) {
125 private String toBaseString(final Object o) {
120126 return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
121127 }
122128
135141 // Gary Gregory - 2003-03-12 - ggregory@seagullsw.com
136142 //
137143
138 public void assertReflectionArray(String expected, Object actual) {
144 public void assertReflectionArray(final String expected, final Object actual) {
139145 if (actual == null) {
140146 // Until ToStringBuilder supports null objects.
141147 return;
149155 @Test
150156 public void testReflectionObjectArray() {
151157 Object[] array = new Object[] { null, base, new int[] { 3, 6 } };
152 String baseStr = this.toBaseString(array);
153 assertEquals(baseStr + "[{<null>,5,{3,6}}]", ToStringBuilder.reflectionToString(array));
154 array = null;
155 assertReflectionArray("<null>", array);
156 this.validateNullToStringStyleRegistry();
158 final String baseString = this.toBaseString(array);
159 assertEquals(baseString + "[{<null>,5,{3,6}}]", ToStringBuilder.reflectionToString(array));
160 array = null;
161 assertReflectionArray("<null>", array);
157162 }
158163
159164 @Test
160165 public void testReflectionLongArray() {
161166 long[] array = new long[] { 1, 2, -3, 4 };
162 String baseStr = this.toBaseString(array);
163 assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
164 array = null;
165 assertReflectionArray("<null>", array);
166 this.validateNullToStringStyleRegistry();
167 final String baseString = this.toBaseString(array);
168 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
169 array = null;
170 assertReflectionArray("<null>", array);
167171 }
168172
169173 @Test
170174 public void testReflectionIntArray() {
171175 int[] array = new int[] { 1, 2, -3, 4 };
172 String baseStr = this.toBaseString(array);
173 assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
174 array = null;
175 assertReflectionArray("<null>", array);
176 this.validateNullToStringStyleRegistry();
176 final String baseString = this.toBaseString(array);
177 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
178 array = null;
179 assertReflectionArray("<null>", array);
177180 }
178181
179182 @Test
180183 public void testReflectionShortArray() {
181184 short[] array = new short[] { 1, 2, -3, 4 };
182 String baseStr = this.toBaseString(array);
183 assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
184 array = null;
185 assertReflectionArray("<null>", array);
186 this.validateNullToStringStyleRegistry();
185 final String baseString = this.toBaseString(array);
186 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
187 array = null;
188 assertReflectionArray("<null>", array);
187189 }
188190
189191 @Test
190192 public void testReflectionyteArray() {
191193 byte[] array = new byte[] { 1, 2, -3, 4 };
192 String baseStr = this.toBaseString(array);
193 assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
194 array = null;
195 assertReflectionArray("<null>", array);
196 this.validateNullToStringStyleRegistry();
194 final String baseString = this.toBaseString(array);
195 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
196 array = null;
197 assertReflectionArray("<null>", array);
197198 }
198199
199200 @Test
200201 public void testReflectionCharArray() {
201202 char[] array = new char[] { 'A', '2', '_', 'D' };
202 String baseStr = this.toBaseString(array);
203 assertEquals(baseStr + "[{A,2,_,D}]", ToStringBuilder.reflectionToString(array));
204 array = null;
205 assertReflectionArray("<null>", array);
206 this.validateNullToStringStyleRegistry();
203 final String baseString = this.toBaseString(array);
204 assertEquals(baseString + "[{A,2,_,D}]", ToStringBuilder.reflectionToString(array));
205 array = null;
206 assertReflectionArray("<null>", array);
207207 }
208208
209209 @Test
210210 public void testReflectionDoubleArray() {
211211 double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 };
212 String baseStr = this.toBaseString(array);
213 assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
214 array = null;
215 assertReflectionArray("<null>", array);
216 this.validateNullToStringStyleRegistry();
212 final String baseString = this.toBaseString(array);
213 assertEquals(baseString + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
214 array = null;
215 assertReflectionArray("<null>", array);
217216 }
218217
219218 @Test
220219 public void testReflectionFloatArray() {
221220 float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f };
222 String baseStr = this.toBaseString(array);
223 assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
224 array = null;
225 assertReflectionArray("<null>", array);
226 this.validateNullToStringStyleRegistry();
221 final String baseString = this.toBaseString(array);
222 assertEquals(baseString + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
223 array = null;
224 assertReflectionArray("<null>", array);
227225 }
228226
229227 @Test
230228 public void testReflectionBooleanArray() {
231229 boolean[] array = new boolean[] { true, false, false };
232 String baseStr = this.toBaseString(array);
233 assertEquals(baseStr + "[{true,false,false}]", ToStringBuilder.reflectionToString(array));
234 array = null;
235 assertReflectionArray("<null>", array);
236 this.validateNullToStringStyleRegistry();
230 final String baseString = this.toBaseString(array);
231 assertEquals(baseString + "[{true,false,false}]", ToStringBuilder.reflectionToString(array));
232 array = null;
233 assertReflectionArray("<null>", array);
237234 }
238235
239236 // Reflection Array Array tests
241238 @Test
242239 public void testReflectionFloatArrayArray() {
243240 float[][] array = new float[][] { { 1.0f, 2.29686f }, null, { Float.NaN } };
244 String baseStr = this.toBaseString(array);
245 assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
246 array = null;
247 assertReflectionArray("<null>", array);
248 this.validateNullToStringStyleRegistry();
241 final String baseString = this.toBaseString(array);
242 assertEquals(baseString + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
243 array = null;
244 assertReflectionArray("<null>", array);
249245 }
250246
251247
252248 @Test
253249 public void testReflectionLongArrayArray() {
254250 long[][] array = new long[][] { { 1, 2 }, null, { 5 } };
255 String baseStr = this.toBaseString(array);
256 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
257 array = null;
258 assertReflectionArray("<null>", array);
259 this.validateNullToStringStyleRegistry();
251 final String baseString = this.toBaseString(array);
252 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
253 array = null;
254 assertReflectionArray("<null>", array);
260255 }
261256
262257 @Test
263258 public void testReflectionIntArrayArray() {
264259 int[][] array = new int[][] { { 1, 2 }, null, { 5 } };
265 String baseStr = this.toBaseString(array);
266 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
267 array = null;
268 assertReflectionArray("<null>", array);
269 this.validateNullToStringStyleRegistry();
260 final String baseString = this.toBaseString(array);
261 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
262 array = null;
263 assertReflectionArray("<null>", array);
270264 }
271265
272266 @Test
273267 public void testReflectionhortArrayArray() {
274268 short[][] array = new short[][] { { 1, 2 }, null, { 5 } };
275 String baseStr = this.toBaseString(array);
276 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
277 array = null;
278 assertReflectionArray("<null>", array);
279 this.validateNullToStringStyleRegistry();
269 final String baseString = this.toBaseString(array);
270 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
271 array = null;
272 assertReflectionArray("<null>", array);
280273 }
281274
282275 @Test
283276 public void testReflectionByteArrayArray() {
284277 byte[][] array = new byte[][] { { 1, 2 }, null, { 5 } };
285 String baseStr = this.toBaseString(array);
286 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
287 array = null;
288 assertReflectionArray("<null>", array);
289 this.validateNullToStringStyleRegistry();
278 final String baseString = this.toBaseString(array);
279 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
280 array = null;
281 assertReflectionArray("<null>", array);
290282 }
291283
292284 @Test
293285 public void testReflectionCharArrayArray() {
294286 char[][] array = new char[][] { { 'A', 'B' }, null, { 'p' } };
295 String baseStr = this.toBaseString(array);
296 assertEquals(baseStr + "[{{A,B},<null>,{p}}]", ToStringBuilder.reflectionToString(array));
297 array = null;
298 assertReflectionArray("<null>", array);
299 this.validateNullToStringStyleRegistry();
287 final String baseString = this.toBaseString(array);
288 assertEquals(baseString + "[{{A,B},<null>,{p}}]", ToStringBuilder.reflectionToString(array));
289 array = null;
290 assertReflectionArray("<null>", array);
300291 }
301292
302293 @Test
303294 public void testReflectionDoubleArrayArray() {
304295 double[][] array = new double[][] { { 1.0, 2.29686 }, null, { Double.NaN } };
305 String baseStr = this.toBaseString(array);
306 assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
307 array = null;
308 assertReflectionArray("<null>", array);
309 this.validateNullToStringStyleRegistry();
296 final String baseString = this.toBaseString(array);
297 assertEquals(baseString + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
298 array = null;
299 assertReflectionArray("<null>", array);
310300 }
311301
312302 @Test
313303 public void testReflectionBooleanArrayArray() {
314304 boolean[][] array = new boolean[][] { { true, false }, null, { false } };
315 String baseStr = this.toBaseString(array);
316 assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
317 assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
318 array = null;
319 assertReflectionArray("<null>", array);
320 this.validateNullToStringStyleRegistry();
305 final String baseString = this.toBaseString(array);
306 assertEquals(baseString + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
307 assertEquals(baseString + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
308 array = null;
309 assertReflectionArray("<null>", array);
321310 }
322311
323312 // Reflection hierarchy tests
324313 @Test
325314 public void testReflectionHierarchyArrayList() {
326 List<Object> base = new ArrayList<Object>();
327 String baseStr = this.toBaseString(base);
328315 // note, the test data depends on the internal representation of the ArrayList, which may differ between JDK versions and vendors
329 String expectedWithTransients = baseStr + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]";
330 String toStringWithTransients = ToStringBuilder.reflectionToString(base, null, true);
316 // representation different for IBM JDK 1.6.0, LANG-727
317 assumeFalse("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION));
318 assumeFalse("Oracle Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".compareTo(SystemUtils.JAVA_SPECIFICATION_VERSION) < 0);
319 final List<Object> list = new ArrayList<Object>();
320 final String baseString = this.toBaseString(list);
321 final String expectedWithTransients = baseString + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]";
322 final String toStringWithTransients = ToStringBuilder.reflectionToString(list, null, true);
331323 if (!expectedWithTransients.equals(toStringWithTransients)) {
332 // representation different for IBM JDK 1.6.0, LANG-727
333 if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) {
334 assertEquals(expectedWithTransients, toStringWithTransients);
335 }
336 }
337 String expectedWithoutTransients = baseStr + "[size=0]";
338 String toStringWithoutTransients = ToStringBuilder.reflectionToString(base, null, false);
324 assertEquals(expectedWithTransients, toStringWithTransients);
325 }
326 final String expectedWithoutTransients = baseString + "[size=0]";
327 final String toStringWithoutTransients = ToStringBuilder.reflectionToString(list, null, false);
339328 if (!expectedWithoutTransients.equals(toStringWithoutTransients)) {
340 // representation different for IBM JDK 1.6.0, LANG-727
341 if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) {
342 assertEquals(expectedWithoutTransients, toStringWithoutTransients);
343 }
344 }
345 this.validateNullToStringStyleRegistry();
329 assertEquals(expectedWithoutTransients, toStringWithoutTransients);
330 }
346331 }
347332
348333 @Test
349334 public void testReflectionHierarchy() {
350 ReflectionTestFixtureA baseA = new ReflectionTestFixtureA();
351 String baseStr = this.toBaseString(baseA);
352 assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA));
353 assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null));
354 assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false));
355 assertEquals(baseStr + "[a=a,transientA=t]", ToStringBuilder.reflectionToString(baseA, null, true));
356 assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, null));
357 assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, Object.class));
358 assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, ReflectionTestFixtureA.class));
359
360 ReflectionTestFixtureB baseB = new ReflectionTestFixtureB();
361 baseStr = this.toBaseString(baseB);
362 assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
363 assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
364 assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null));
365 assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false));
366 assertEquals(baseStr + "[b=b,transientB=t,a=a,transientA=t]", ToStringBuilder.reflectionToString(baseB, null, true));
367 assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, null));
368 assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, Object.class));
369 assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureA.class));
370 assertEquals(baseStr + "[b=b]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureB.class));
371 this.validateNullToStringStyleRegistry();
335 final ReflectionTestFixtureA baseA = new ReflectionTestFixtureA();
336 String baseString = this.toBaseString(baseA);
337 assertEquals(baseString + "[a=a]", ToStringBuilder.reflectionToString(baseA));
338 assertEquals(baseString + "[a=a]", ToStringBuilder.reflectionToString(baseA, null));
339 assertEquals(baseString + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false));
340 assertEquals(baseString + "[a=a,transientA=t]", ToStringBuilder.reflectionToString(baseA, null, true));
341 assertEquals(baseString + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, null));
342 assertEquals(baseString + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, Object.class));
343 assertEquals(baseString + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, ReflectionTestFixtureA.class));
344
345 final ReflectionTestFixtureB baseB = new ReflectionTestFixtureB();
346 baseString = this.toBaseString(baseB);
347 assertEquals(baseString + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
348 assertEquals(baseString + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
349 assertEquals(baseString + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null));
350 assertEquals(baseString + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false));
351 assertEquals(baseString + "[b=b,transientB=t,a=a,transientA=t]", ToStringBuilder.reflectionToString(baseB, null, true));
352 assertEquals(baseString + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, null));
353 assertEquals(baseString + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, Object.class));
354 assertEquals(baseString + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureA.class));
355 assertEquals(baseString + "[b=b]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureB.class));
372356 }
373357
374358 static class ReflectionTestFixtureA {
375359 @SuppressWarnings("unused")
376 private char a='a';
360 private final char a='a';
377361 @SuppressWarnings("unused")
378362 private transient char transientA='t';
379363 }
380364
381365 static class ReflectionTestFixtureB extends ReflectionTestFixtureA {
382366 @SuppressWarnings("unused")
383 private char b='b';
367 private final char b='b';
384368 @SuppressWarnings("unused")
385369 private transient char transientB='t';
386370 }
387371
388372 @Test
389373 public void testInnerClassReflection() {
390 Outer outer = new Outer();
374 final Outer outer = new Outer();
391375 assertEquals(toBaseString(outer) + "[inner=" + toBaseString(outer.inner) + "[]]", outer.toString());
392376 }
393377
412396 */
413397 @Test
414398 public void testReflectionArrayCycle() throws Exception {
415 Object[] objects = new Object[1];
399 final Object[] objects = new Object[1];
416400 objects[0] = objects;
417401 assertEquals(
418402 this.toBaseString(objects) + "[{" + this.toBaseString(objects) + "}]",
419403 ToStringBuilder.reflectionToString(objects));
420 this.validateNullToStringStyleRegistry();
421404 }
422405
423406 /**
425408 */
426409 @Test
427410 public void testReflectionArrayCycleLevel2() throws Exception {
428 Object[] objects = new Object[1];
429 Object[] objectsLevel2 = new Object[1];
411 final Object[] objects = new Object[1];
412 final Object[] objectsLevel2 = new Object[1];
430413 objects[0] = objectsLevel2;
431414 objectsLevel2[0] = objects;
432415 assertEquals(
435418 assertEquals(
436419 this.toBaseString(objectsLevel2) + "[{{" + this.toBaseString(objectsLevel2) + "}}]",
437420 ToStringBuilder.reflectionToString(objectsLevel2));
438 this.validateNullToStringStyleRegistry();
439421 }
440422
441423 @Test
442424 public void testReflectionArrayArrayCycle() throws Exception {
443 Object[][] objects = new Object[2][2];
425 final Object[][] objects = new Object[2][2];
444426 objects[0][0] = objects;
445427 objects[0][1] = objects;
446428 objects[1][0] = objects;
447429 objects[1][1] = objects;
448 String basicToString = this.toBaseString(objects);
430 final String basicToString = this.toBaseString(objects);
449431 assertEquals(
450432 basicToString
451433 + "[{{"
458440 + basicToString
459441 + "}}]",
460442 ToStringBuilder.reflectionToString(objects));
461 this.validateNullToStringStyleRegistry();
462443 }
463444
464445 /**
494475 public SimpleReflectionTestFixture() {
495476 }
496477
497 public SimpleReflectionTestFixture(Object o) {
478 public SimpleReflectionTestFixture(final Object o) {
498479 this.o = o;
499480 }
500481
506487
507488 private static class SelfInstanceVarReflectionTestFixture {
508489 @SuppressWarnings("unused")
509 private SelfInstanceVarReflectionTestFixture typeIsSelf;
490 private final SelfInstanceVarReflectionTestFixture typeIsSelf;
510491
511492 public SelfInstanceVarReflectionTestFixture() {
512493 this.typeIsSelf = this;
520501
521502 private static class SelfInstanceTwoVarsReflectionTestFixture {
522503 @SuppressWarnings("unused")
523 private SelfInstanceTwoVarsReflectionTestFixture typeIsSelf;
524 private String otherType = "The Other Type";
504 private final SelfInstanceTwoVarsReflectionTestFixture typeIsSelf;
505 private final String otherType = "The Other Type";
525506
526507 public SelfInstanceTwoVarsReflectionTestFixture() {
527508 this.typeIsSelf = this;
545526 */
546527 @Test
547528 public void testSimpleReflectionObjectCycle() throws Exception {
548 SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture();
529 final SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture();
549530 simple.o = simple;
550531 assertEquals(this.toBaseString(simple) + "[o=" + this.toBaseString(simple) + "]", simple.toString());
551 this.validateNullToStringStyleRegistry();
552532 }
553533
554534 /**
558538 */
559539 @Test
560540 public void testSelfInstanceVarReflectionObjectCycle() throws Exception {
561 SelfInstanceVarReflectionTestFixture test = new SelfInstanceVarReflectionTestFixture();
541 final SelfInstanceVarReflectionTestFixture test = new SelfInstanceVarReflectionTestFixture();
562542 assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + "]", test.toString());
563 this.validateNullToStringStyleRegistry();
564543 }
565544
566545 /**
571550 */
572551 @Test
573552 public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception {
574 SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture();
553 final SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture();
575554 assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + ",otherType=" + test.getOtherType().toString() + "]", test.toString());
576 this.validateNullToStringStyleRegistry();
577555 }
578556
579557
584562 */
585563 @Test
586564 public void testReflectionObjectCycle() throws Exception {
587 ReflectionTestCycleA a = new ReflectionTestCycleA();
588 ReflectionTestCycleB b = new ReflectionTestCycleB();
565 final ReflectionTestCycleA a = new ReflectionTestCycleA();
566 final ReflectionTestCycleB b = new ReflectionTestCycleB();
589567 a.b = b;
590568 b.a = a;
591569 assertEquals(
592570 this.toBaseString(a) + "[b=" + this.toBaseString(b) + "[a=" + this.toBaseString(a) + "]]",
593571 a.toString());
594 this.validateNullToStringStyleRegistry();
595572 }
596573
597574 /**
602579 */
603580 @Test
604581 public void testReflectionArrayAndObjectCycle() throws Exception {
605 Object[] objects = new Object[1];
606 SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects);
582 final Object[] objects = new Object[1];
583 final SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects);
607584 objects[0] = simple;
608585 assertEquals(
609586 this.toBaseString(objects)
620597 + this.toBaseString(simple)
621598 + "}]",
622599 ToStringBuilder.reflectionToString(simple));
623 this.validateNullToStringStyleRegistry();
624600 }
625601
626602 void validateNullToStringStyleRegistry() {
627 if (ToStringStyle.getRegistry() != null) {
628 System.out.println(ToStringStyle.getRegistry());
629 }
630
631 assertNull(ToStringStyle.getRegistry());
603 final Map<Object, Object> registry = ToStringStyle.getRegistry();
604 assertNull("Expected null, actual: "+registry, registry);
632605 }
633606 // End: Reflection cycle tests
634607
654627
655628 @Test
656629 public void testObject() {
657 Integer i3 = Integer.valueOf(3);
658 Integer i4 = Integer.valueOf(4);
630 final Integer i3 = Integer.valueOf(3);
631 final Integer i4 = Integer.valueOf(4);
659632 assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).toString());
660633 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString());
661634 assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).toString());
672645
673646 @Test
674647 public void testObjectBuild() {
675 Integer i3 = Integer.valueOf(3);
676 Integer i4 = Integer.valueOf(4);
648 final Integer i3 = Integer.valueOf(3);
649 final Integer i4 = Integer.valueOf(4);
677650 assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).build());
678651 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).build());
679652 assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).build());
919892
920893 @Test
921894 public void testObjectCycle() {
922 ObjectCycle a = new ObjectCycle();
923 ObjectCycle b = new ObjectCycle();
895 final ObjectCycle a = new ObjectCycle();
896 final ObjectCycle b = new ObjectCycle();
924897 a.obj = b;
925898 b.obj = a;
926899
927 String expected = toBaseString(a) + "[" + toBaseString(b) + "[" + toBaseString(a) + "]]";
900 final String expected = toBaseString(a) + "[" + toBaseString(b) + "[" + toBaseString(a) + "]]";
928901 assertEquals(expected, a.toString());
929 validateNullToStringStyleRegistry();
930902 }
931903
932904 static class ObjectCycle {
940912
941913 @Test
942914 public void testSimpleReflectionStatics() {
943 SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture();
915 final SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture();
944916 assertEquals(
945917 this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
946918 ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class));
960932 */
961933 @Test
962934 public void testReflectionStatics() {
963 ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture();
935 final ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture();
964936 assertEquals(
965937 this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]",
966938 ReflectionToStringBuilder.toString(instance1, null, false, true, ReflectionStaticFieldsFixture.class));
980952 */
981953 @Test
982954 public void testInheritedReflectionStatics() {
983 InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture();
955 final InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture();
984956 assertEquals(
985957 this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890]",
986958 ReflectionToStringBuilder.toString(instance1, null, false, true, InheritedReflectionStaticFieldsFixture.class));
1020992 * @return the String result
1021993 * @throws IllegalArgumentException if the Object is <code>null</code>
1022994 */
1023 public <T> String toStringWithStatics(T object, ToStringStyle style, Class<? super T> reflectUpToClass) {
995 public <T> String toStringWithStatics(final T object, final ToStringStyle style, final Class<? super T> reflectUpToClass) {
1024996 return ReflectionToStringBuilder.toString(object, style, false, true, reflectUpToClass);
1025997 }
1026998
10291001 */
10301002 @Test
10311003 public void test_setUpToClass_valid() {
1032 Integer val = Integer.valueOf(5);
1033 ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
1004 final Integer val = Integer.valueOf(5);
1005 final ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
10341006 test.setUpToClass(Number.class);
1007 test.toString();
10351008 }
10361009
10371010 /**
10381011 * Tests ReflectionToStringBuilder setUpToClass().
10391012 */
1040 @Test
1013 @Test(expected=IllegalArgumentException.class)
10411014 public void test_setUpToClass_invalid() {
1042 Integer val = Integer.valueOf(5);
1043 ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
1015 final Integer val = Integer.valueOf(5);
1016 final ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
10441017 try {
10451018 test.setUpToClass(String.class);
1046 fail();
1047 } catch (IllegalArgumentException ex) {
1048 // expected
1019 } finally {
1020 test.toString();
10491021 }
10501022 }
10511023
10981070
10991071 @Test
11001072 public void testAppendToStringUsingMultiLineStyle() {
1101 MultiLineTestObject obj = new MultiLineTestObject();
1102 ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
1073 final MultiLineTestObject obj = new MultiLineTestObject();
1074 final ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
11031075 .appendToString(obj.toString());
11041076 assertEquals(testBuilder.toString().indexOf("testInt=31337"), -1);
11051077 }
4242 * @see <a href="https://issues.apache.org/jira/browse/LANG-762">[LANG-762] Handle or document ReflectionToStringBuilder
4343 * and ToStringBuilder for collections that are not thread safe</a>
4444 * @since 3.1
45 * @version $Id: ToStringStyleConcurrencyTest.java 1199816 2011-11-09 16:11:34Z bayard $
45 * @version $Id: ToStringStyleConcurrencyTest.java 1436770 2013-01-22 07:09:45Z ggregory $
4646 */
4747 public class ToStringStyleConcurrencyTest {
4848
4949 static class CollectionHolder<T extends Collection<?>> {
5050 T collection;
5151
52 CollectionHolder(T collection) {
52 CollectionHolder(final T collection) {
5353 this.collection = collection;
5454 }
5555 }
8888 // Create a thread pool with two threads to cause the most contention on the underlying resource.
8989 final ExecutorService threadPool = Executors.newFixedThreadPool(2);
9090 // Consumes toStrings
91 Callable<Integer> consumer = new Callable<Integer>() {
91 final Callable<Integer> consumer = new Callable<Integer>() {
92 @Override
9293 public Integer call() {
9394 for (int i = 0; i < REPEAT; i++) {
9495 // Calls ToStringStyle
9596 new ToStringBuilder(holder).append(holder.collection);
9697 }
97 return REPEAT;
98 return Integer.valueOf(REPEAT);
9899 }
99100 };
100 Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
101 final Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
101102 tasks.add(consumer);
102103 tasks.add(consumer);
103104 final List<Future<Integer>> futures = threadPool.invokeAll(tasks);
104 for (Future<Integer> future : futures) {
105 for (final Future<Integer> future : futures) {
105106 future.get();
106107 }
107108 }
2222 /**
2323 * Test case for ToStringStyle.
2424 *
25 * @version $Id: ToStringStyleTest.java 1185695 2011-10-18 14:47:48Z ggregory $
25 * @version $Id: ToStringStyleTest.java 1533541 2013-10-18 16:33:52Z sebb $
2626 */
2727 public class ToStringStyleTest {
2828
2929 private static class ToStringStyleImpl extends ToStringStyle {
30 private static final long serialVersionUID = 1L;
31
3032 }
3133
3234 //-----------------------------------------------------------------------
3335 @Test
3436 public void testSetArrayStart() {
35 ToStringStyle style = new ToStringStyleImpl();
37 final ToStringStyle style = new ToStringStyleImpl();
3638 style.setArrayStart(null);
3739 assertEquals("", style.getArrayStart());
3840 }
3941
4042 @Test
4143 public void testSetArrayEnd() {
42 ToStringStyle style = new ToStringStyleImpl();
44 final ToStringStyle style = new ToStringStyleImpl();
4345 style.setArrayEnd(null);
4446 assertEquals("", style.getArrayEnd());
4547 }
4648
4749 @Test
4850 public void testSetArraySeparator() {
49 ToStringStyle style = new ToStringStyleImpl();
51 final ToStringStyle style = new ToStringStyleImpl();
5052 style.setArraySeparator(null);
5153 assertEquals("", style.getArraySeparator());
5254 }
5355
5456 @Test
5557 public void testSetContentStart() {
56 ToStringStyle style = new ToStringStyleImpl();
58 final ToStringStyle style = new ToStringStyleImpl();
5759 style.setContentStart(null);
5860 assertEquals("", style.getContentStart());
5961 }
6062
6163 @Test
6264 public void testSetContentEnd() {
63 ToStringStyle style = new ToStringStyleImpl();
65 final ToStringStyle style = new ToStringStyleImpl();
6466 style.setContentEnd(null);
6567 assertEquals("", style.getContentEnd());
6668 }
6769
6870 @Test
6971 public void testSetFieldNameValueSeparator() {
70 ToStringStyle style = new ToStringStyleImpl();
72 final ToStringStyle style = new ToStringStyleImpl();
7173 style.setFieldNameValueSeparator(null);
7274 assertEquals("", style.getFieldNameValueSeparator());
7375 }
7476
7577 @Test
7678 public void testSetFieldSeparator() {
77 ToStringStyle style = new ToStringStyleImpl();
79 final ToStringStyle style = new ToStringStyleImpl();
7880 style.setFieldSeparator(null);
7981 assertEquals("", style.getFieldSeparator());
8082 }
8183
8284 @Test
8385 public void testSetNullText() {
84 ToStringStyle style = new ToStringStyleImpl();
86 final ToStringStyle style = new ToStringStyleImpl();
8587 style.setNullText(null);
8688 assertEquals("", style.getNullText());
8789 }
8890
8991 @Test
9092 public void testSetSizeStartText() {
91 ToStringStyle style = new ToStringStyleImpl();
93 final ToStringStyle style = new ToStringStyleImpl();
9294 style.setSizeStartText(null);
9395 assertEquals("", style.getSizeStartText());
9496 }
9597
9698 @Test
9799 public void testSetSizeEndText() {
98 ToStringStyle style = new ToStringStyleImpl();
100 final ToStringStyle style = new ToStringStyleImpl();
99101 style.setSizeEndText(null);
100102 assertEquals("", style.getSizeEndText());
101103 }
102104
103105 @Test
104106 public void testSetSummaryObjectStartText() {
105 ToStringStyle style = new ToStringStyleImpl();
107 final ToStringStyle style = new ToStringStyleImpl();
106108 style.setSummaryObjectStartText(null);
107109 assertEquals("", style.getSummaryObjectStartText());
108110 }
109111
110112 @Test
111113 public void testSetSummaryObjectEndText() {
112 ToStringStyle style = new ToStringStyleImpl();
114 final ToStringStyle style = new ToStringStyleImpl();
113115 style.setSummaryObjectEndText(null);
114116 assertEquals("", style.getSummaryObjectEndText());
115117 }
3333 * tests are executed.
3434 * </p>
3535 *
36 * @version $Id: AbstractConcurrentInitializerTest.java 1088899 2011-04-05 05:31:27Z bayard $
36 * @version $Id: AbstractConcurrentInitializerTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3737 */
3838 public abstract class AbstractConcurrentInitializerTest {
3939 /**
5050 */
5151 @Test
5252 public void testGetMultipleTimes() throws ConcurrentException {
53 ConcurrentInitializer<Object> initializer = createInitializer();
54 Object obj = initializer.get();
53 final ConcurrentInitializer<Object> initializer = createInitializer();
54 final Object obj = initializer.get();
5555 for (int i = 0; i < 10; i++) {
5656 assertEquals("Got different object at " + i, obj, initializer.get());
5757 }
7777 startLatch.await();
7878 // access the initializer
7979 object = initializer.get();
80 } catch (InterruptedException iex) {
80 } catch (final InterruptedException iex) {
8181 // ignore
82 } catch (ConcurrentException cex) {
82 } catch (final ConcurrentException cex) {
8383 object = cex;
8484 }
8585 }
8686 }
8787
88 GetThread[] threads = new GetThread[threadCount];
88 final GetThread[] threads = new GetThread[threadCount];
8989 for (int i = 0; i < threadCount; i++) {
9090 threads[i] = new GetThread();
9191 threads[i].start();
9393
9494 // fire all threads and wait until they are ready
9595 startLatch.countDown();
96 for (Thread t : threads) {
96 for (final Thread t : threads) {
9797 t.join();
9898 }
9999
100100 // check results
101 Object managedObject = initializer.get();
102 for (GetThread t : threads) {
101 final Object managedObject = initializer.get();
102 for (final GetThread t : threads) {
103103 assertEquals("Wrong object", managedObject, t.object);
104104 }
105105 }
1515 */
1616 package org.apache.commons.lang3.concurrent;
1717
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1820 import java.util.concurrent.CountDownLatch;
1921 import java.util.concurrent.ExecutorService;
2022 import java.util.concurrent.Executors;
2123 import java.util.concurrent.TimeUnit;
2224 import java.util.concurrent.atomic.AtomicReference;
2325
24 import junit.framework.TestCase;
25
26 public class BackgroundInitializerTest extends TestCase {
26 public class BackgroundInitializerTest {
2727 /**
2828 * Helper method for checking whether the initialize() method was correctly
2929 * called. start() must already have been invoked.
3030 *
3131 * @param init the initializer to test
3232 */
33 private void checkInitialize(BackgroundInitializerTestImpl init) {
34 try {
35 Integer result = init.get();
33 private void checkInitialize(final BackgroundInitializerTestImpl init) {
34 try {
35 final Integer result = init.get();
3636 assertEquals("Wrong result", 1, result.intValue());
3737 assertEquals("Wrong number of invocations", 1, init.initializeCalls);
3838 assertNotNull("No future", init.getFuture());
39 } catch (ConcurrentException cex) {
39 } catch (final ConcurrentException cex) {
4040 fail("Unexpected exception: " + cex);
4141 }
4242 }
4444 /**
4545 * Tests whether initialize() is invoked.
4646 */
47 @Test
4748 public void testInitialize() {
48 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
49 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
4950 init.start();
5051 checkInitialize(init);
5152 }
5455 * Tries to obtain the executor before start(). It should not have been
5556 * initialized yet.
5657 */
58 @Test
5759 public void testGetActiveExecutorBeforeStart() {
58 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
60 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
5961 assertNull("Got an executor", init.getActiveExecutor());
6062 }
6163
6264 /**
6365 * Tests whether an external executor is correctly detected.
6466 */
67 @Test
6568 public void testGetActiveExecutorExternal() {
66 ExecutorService exec = Executors.newSingleThreadExecutor();
67 try {
68 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(
69 final ExecutorService exec = Executors.newSingleThreadExecutor();
70 try {
71 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(
6972 exec);
7073 init.start();
7174 assertSame("Wrong executor", exec, init.getActiveExecutor());
7881 /**
7982 * Tests getActiveExecutor() for a temporary executor.
8083 */
84 @Test
8185 public void testGetActiveExecutorTemp() {
82 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
86 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
8387 init.start();
8488 assertNotNull("No active executor", init.getActiveExecutor());
8589 checkInitialize(init);
8993 * Tests the execution of the background task if a temporary executor has to
9094 * be created.
9195 */
96 @Test
9297 public void testInitializeTempExecutor() {
93 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
98 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
9499 assertTrue("Wrong result of start()", init.start());
95100 checkInitialize(init);
96101 assertTrue("Executor not shutdown", init.getActiveExecutor()
101106 * Tests whether an external executor can be set using the
102107 * setExternalExecutor() method.
103108 */
109 @Test
104110 public void testSetExternalExecutor() throws Exception {
105 ExecutorService exec = Executors.newCachedThreadPool();
106 try {
107 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
111 final ExecutorService exec = Executors.newCachedThreadPool();
112 try {
113 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
108114 init.setExternalExecutor(exec);
109115 assertEquals("Wrong executor service", exec, init
110116 .getExternalExecutor());
120126 /**
121127 * Tests that setting an executor after start() causes an exception.
122128 */
129 @Test
123130 public void testSetExternalExecutorAfterStart() throws ConcurrentException {
124 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
131 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
125132 init.start();
126133 try {
127134 init.setExternalExecutor(Executors.newSingleThreadExecutor());
128135 fail("Could set executor after start()!");
129 } catch (IllegalStateException istex) {
136 } catch (final IllegalStateException istex) {
130137 init.get();
131138 }
132139 }
135142 * Tests invoking start() multiple times. Only the first invocation should
136143 * have an effect.
137144 */
145 @Test
138146 public void testStartMultipleTimes() {
139 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
147 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
140148 assertTrue("Wrong result for start()", init.start());
141149 for (int i = 0; i < 10; i++) {
142150 assertFalse("Could start again", init.start());
147155 /**
148156 * Tests calling get() before start(). This should cause an exception.
149157 */
158 @Test(expected=IllegalStateException.class)
150159 public void testGetBeforeStart() throws ConcurrentException {
151 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
152 try {
153 init.get();
154 fail("Could call get() before start()!");
155 } catch (IllegalStateException istex) {
156 // ok
157 }
160 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
161 init.get();
158162 }
159163
160164 /**
161165 * Tests the get() method if background processing causes a runtime
162166 * exception.
163167 */
168 @Test
164169 public void testGetRuntimeException() throws Exception {
165 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
166 RuntimeException rex = new RuntimeException();
170 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
171 final RuntimeException rex = new RuntimeException();
167172 init.ex = rex;
168173 init.start();
169174 try {
170175 init.get();
171176 fail("Exception not thrown!");
172 } catch (Exception ex) {
177 } catch (final Exception ex) {
173178 assertEquals("Runtime exception not thrown", rex, ex);
174179 }
175180 }
178183 * Tests the get() method if background processing causes a checked
179184 * exception.
180185 */
186 @Test
181187 public void testGetCheckedException() throws Exception {
182 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
183 Exception ex = new Exception();
188 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
189 final Exception ex = new Exception();
184190 init.ex = ex;
185191 init.start();
186192 try {
187193 init.get();
188194 fail("Exception not thrown!");
189 } catch (ConcurrentException cex) {
195 } catch (final ConcurrentException cex) {
190196 assertEquals("Exception not thrown", ex, cex.getCause());
191197 }
192198 }
194200 /**
195201 * Tests the get() method if waiting for the initialization is interrupted.
196202 */
203 @Test
197204 public void testGetInterruptedException() throws Exception {
198 ExecutorService exec = Executors.newSingleThreadExecutor();
205 final ExecutorService exec = Executors.newSingleThreadExecutor();
199206 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(
200207 exec);
201208 final CountDownLatch latch1 = new CountDownLatch(1);
202209 init.shouldSleep = true;
203210 init.start();
204211 final AtomicReference<InterruptedException> iex = new AtomicReference<InterruptedException>();
205 Thread getThread = new Thread() {
212 final Thread getThread = new Thread() {
206213 @Override
207214 public void run() {
208215 try {
209216 init.get();
210 } catch (ConcurrentException cex) {
217 } catch (final ConcurrentException cex) {
211218 if (cex.getCause() instanceof InterruptedException) {
212219 iex.set((InterruptedException) cex.getCause());
213220 }
228235 /**
229236 * Tests isStarted() before start() was called.
230237 */
238 @Test
231239 public void testIsStartedFalse() {
232 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
240 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
233241 assertFalse("Already started", init.isStarted());
234242 }
235243
236244 /**
237245 * Tests isStarted() after start().
238246 */
247 @Test
239248 public void testIsStartedTrue() {
240 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
249 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
241250 init.start();
242251 assertTrue("Not started", init.isStarted());
243252 }
245254 /**
246255 * Tests isStarted() after the background task has finished.
247256 */
257 @Test
248258 public void testIsStartedAfterGet() {
249 BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
259 final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
250260 init.start();
251261 checkInitialize(init);
252262 assertTrue("Not started", init.isStarted());
271281 super();
272282 }
273283
274 public BackgroundInitializerTestImpl(ExecutorService exec) {
284 public BackgroundInitializerTestImpl(final ExecutorService exec) {
275285 super(exec);
276286 }
277287
287297 if (shouldSleep) {
288298 Thread.sleep(60000L);
289299 }
290 return ++initializeCalls;
300 return Integer.valueOf(++initializeCalls);
291301 }
292302 }
293303 }
3232 /**
3333 * Test class for {@code BasicThreadFactory}.
3434 *
35 * @version $Id: BasicThreadFactoryTest.java 979392 2010-07-26 18:09:52Z mbenson $
35 * @version $Id: BasicThreadFactoryTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3636 */
3737 public class BasicThreadFactoryTest {
3838 /** Constant for the test naming pattern. */
5151 *
5252 * @param factory the factory to be checked
5353 */
54 private void checkFactoryDefaults(BasicThreadFactory factory) {
54 private void checkFactoryDefaults(final BasicThreadFactory factory) {
5555 assertNull("Got a naming pattern", factory.getNamingPattern());
5656 assertNull("Got an exception handler", factory
5757 .getUncaughtExceptionHandler());
6565 */
6666 @Test
6767 public void testBuildDefaults() {
68 BasicThreadFactory factory = builder.build();
68 final BasicThreadFactory factory = builder.build();
6969 checkFactoryDefaults(factory);
7070 }
7171
9898 */
9999 @Test
100100 public void testBuilderReset() {
101 ThreadFactory wrappedFactory = EasyMock.createMock(ThreadFactory.class);
102 Thread.UncaughtExceptionHandler exHandler = EasyMock
101 final ThreadFactory wrappedFactory = EasyMock.createMock(ThreadFactory.class);
102 final Thread.UncaughtExceptionHandler exHandler = EasyMock
103103 .createMock(Thread.UncaughtExceptionHandler.class);
104104 EasyMock.replay(wrappedFactory, exHandler);
105105 builder.namingPattern(PATTERN).daemon(true).priority(
106106 Thread.MAX_PRIORITY).uncaughtExceptionHandler(exHandler)
107107 .wrappedFactory(wrappedFactory);
108108 builder.reset();
109 BasicThreadFactory factory = builder.build();
109 final BasicThreadFactory factory = builder.build();
110110 checkFactoryDefaults(factory);
111111 assertNotSame("Wrapped factory not reset", wrappedFactory, factory
112112 .getWrappedFactory());
128128 */
129129 @Test
130130 public void testNewThreadNamingPattern() {
131 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
132 Runnable r = EasyMock.createMock(Runnable.class);
131 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
132 final Runnable r = EasyMock.createMock(Runnable.class);
133133 final int count = 12;
134134 for (int i = 0; i < count; i++) {
135135 EasyMock.expect(wrapped.newThread(r)).andReturn(new Thread());
136136 }
137137 EasyMock.replay(wrapped, r);
138 BasicThreadFactory factory = builder.wrappedFactory(wrapped)
138 final BasicThreadFactory factory = builder.wrappedFactory(wrapped)
139139 .namingPattern(PATTERN).build();
140140 for (int i = 0; i < count; i++) {
141 Thread t = factory.newThread(r);
141 final Thread t = factory.newThread(r);
142142 assertEquals("Wrong thread name", String.format(PATTERN, Long
143143 .valueOf(i + 1)), t.getName());
144144 assertEquals("Wrong thread count", i + 1, factory.getThreadCount());
152152 */
153153 @Test
154154 public void testNewThreadNoNamingPattern() {
155 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
156 Runnable r = EasyMock.createMock(Runnable.class);
155 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
156 final Runnable r = EasyMock.createMock(Runnable.class);
157157 final String name = "unchangedThreadName";
158 Thread t = new Thread(name);
159 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
160 EasyMock.replay(wrapped, r);
161 BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
158 final Thread t = new Thread(name);
159 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
160 EasyMock.replay(wrapped, r);
161 final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
162162 assertSame("Wrong thread", t, factory.newThread(r));
163163 assertEquals("Name was changed", name, t.getName());
164164 EasyMock.verify(wrapped, r);
169169 *
170170 * @param flag the value of the flag
171171 */
172 private void checkDaemonFlag(boolean flag) {
173 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
174 Runnable r = EasyMock.createMock(Runnable.class);
175 Thread t = new Thread();
176 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
177 EasyMock.replay(wrapped, r);
178 BasicThreadFactory factory = builder.wrappedFactory(wrapped).daemon(
172 private void checkDaemonFlag(final boolean flag) {
173 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
174 final Runnable r = EasyMock.createMock(Runnable.class);
175 final Thread t = new Thread();
176 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
177 EasyMock.replay(wrapped, r);
178 final BasicThreadFactory factory = builder.wrappedFactory(wrapped).daemon(
179179 flag).build();
180180 assertSame("Wrong thread", t, factory.newThread(r));
181 assertEquals("Wrong daemon flag", flag, t.isDaemon());
181 assertTrue("Wrong daemon flag", flag == t.isDaemon());
182182 EasyMock.verify(wrapped, r);
183183 }
184184
204204 */
205205 @Test
206206 public void testNewThreadNoDaemonFlag() {
207 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
208 Runnable r1 = EasyMock.createMock(Runnable.class);
209 Runnable r2 = EasyMock.createMock(Runnable.class);
210 Thread t1 = new Thread();
211 Thread t2 = new Thread();
207 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
208 final Runnable r1 = EasyMock.createMock(Runnable.class);
209 final Runnable r2 = EasyMock.createMock(Runnable.class);
210 final Thread t1 = new Thread();
211 final Thread t2 = new Thread();
212212 t1.setDaemon(true);
213213 EasyMock.expect(wrapped.newThread(r1)).andReturn(t1);
214214 EasyMock.expect(wrapped.newThread(r2)).andReturn(t2);
215215 EasyMock.replay(wrapped, r1, r2);
216 BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
216 final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
217217 assertSame("Wrong thread 1", t1, factory.newThread(r1));
218218 assertTrue("No daemon thread", t1.isDaemon());
219219 assertSame("Wrong thread 2", t2, factory.newThread(r2));
226226 */
227227 @Test
228228 public void testNewThreadPriority() {
229 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
230 Runnable r = EasyMock.createMock(Runnable.class);
231 Thread t = new Thread();
229 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
230 final Runnable r = EasyMock.createMock(Runnable.class);
231 final Thread t = new Thread();
232232 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
233233 EasyMock.replay(wrapped, r);
234234 final int priority = Thread.NORM_PRIORITY + 1;
235 BasicThreadFactory factory = builder.wrappedFactory(wrapped).priority(
235 final BasicThreadFactory factory = builder.wrappedFactory(wrapped).priority(
236236 priority).build();
237237 assertSame("Wrong thread", t, factory.newThread(r));
238238 assertEquals("Wrong priority", priority, t.getPriority());
245245 */
246246 @Test
247247 public void testNewThreadNoPriority() {
248 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
249 Runnable r = EasyMock.createMock(Runnable.class);
248 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
249 final Runnable r = EasyMock.createMock(Runnable.class);
250250 final int orgPriority = Thread.NORM_PRIORITY + 1;
251 Thread t = new Thread();
251 final Thread t = new Thread();
252252 t.setPriority(orgPriority);
253253 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
254254 EasyMock.replay(wrapped, r);
255 BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
255 final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
256256 assertSame("Wrong thread", t, factory.newThread(r));
257257 assertEquals("Wrong priority", orgPriority, t.getPriority());
258258 EasyMock.verify(wrapped, r);
263263 */
264264 @Test
265265 public void testNewThreadExHandler() {
266 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
267 Runnable r = EasyMock.createMock(Runnable.class);
268 Thread.UncaughtExceptionHandler handler = EasyMock
266 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
267 final Runnable r = EasyMock.createMock(Runnable.class);
268 final Thread.UncaughtExceptionHandler handler = EasyMock
269269 .createMock(Thread.UncaughtExceptionHandler.class);
270 Thread t = new Thread();
270 final Thread t = new Thread();
271271 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
272272 EasyMock.replay(wrapped, r, handler);
273 BasicThreadFactory factory = builder.wrappedFactory(wrapped)
273 final BasicThreadFactory factory = builder.wrappedFactory(wrapped)
274274 .uncaughtExceptionHandler(handler).build();
275275 assertSame("Wrong thread", t, factory.newThread(r));
276276 assertEquals("Wrong exception handler", handler, t
284284 */
285285 @Test
286286 public void testNewThreadNoExHandler() {
287 ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
288 Runnable r = EasyMock.createMock(Runnable.class);
289 Thread.UncaughtExceptionHandler handler = EasyMock
287 final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
288 final Runnable r = EasyMock.createMock(Runnable.class);
289 final Thread.UncaughtExceptionHandler handler = EasyMock
290290 .createMock(Thread.UncaughtExceptionHandler.class);
291 Thread t = new Thread();
291 final Thread t = new Thread();
292292 t.setUncaughtExceptionHandler(handler);
293293 EasyMock.expect(wrapped.newThread(r)).andReturn(t);
294294 EasyMock.replay(wrapped, r, handler);
295 BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
295 final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
296296 assertSame("Wrong thread", t, factory.newThread(r));
297297 assertEquals("Wrong exception handler", handler, t
298298 .getUncaughtExceptionHandler());
1515 */
1616 package org.apache.commons.lang3.concurrent;
1717
18 import static org.junit.Assert.assertEquals;
19
1820 import java.util.concurrent.Callable;
1921 import java.util.concurrent.ExecutorService;
2022 import java.util.concurrent.Executors;
2123
22 import junit.framework.TestCase;
24 import org.junit.Test;
2325
2426 /**
2527 * Test class for {@code CallableBackgroundInitializer}
2628 *
27 * @version $Id: CallableBackgroundInitializerTest.java 902960 2010-01-25 19:47:41Z sebb $
29 * @version $Id: CallableBackgroundInitializerTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2830 */
29 public class CallableBackgroundInitializerTest extends TestCase {
31 public class CallableBackgroundInitializerTest {
3032 /** Constant for the result of the call() invocation. */
3133 private static final Integer RESULT = Integer.valueOf(42);
3234
3436 * Tries to create an instance without a Callable. This should cause an
3537 * exception.
3638 */
39 @Test(expected=IllegalArgumentException.class)
3740 public void testInitNullCallable() {
38 try {
39 new CallableBackgroundInitializer<Object>(null);
40 fail("Could create instance without a Callable!");
41 } catch (IllegalArgumentException iex) {
42 // ok
43 }
41 new CallableBackgroundInitializer<Object>(null);
4442 }
4543
4644 /**
4745 * Tests whether the executor service is correctly passed to the super
4846 * class.
4947 */
48 @Test
5049 public void testInitExecutor() {
51 ExecutorService exec = Executors.newSingleThreadExecutor();
52 CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<Integer>(
50 final ExecutorService exec = Executors.newSingleThreadExecutor();
51 final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<Integer>(
5352 new TestCallable(), exec);
5453 assertEquals("Executor not set", exec, init.getExternalExecutor());
5554 }
5857 * Tries to pass a null Callable to the constructor that takes an executor.
5958 * This should cause an exception.
6059 */
60 @Test(expected=IllegalArgumentException.class)
6161 public void testInitExecutorNullCallable() {
62 ExecutorService exec = Executors.newSingleThreadExecutor();
63 try {
64 new CallableBackgroundInitializer<Integer>(null, exec);
65 fail("Could create instance without a Callable!");
66 } catch (IllegalArgumentException iex) {
67 // ok
68 }
62 final ExecutorService exec = Executors.newSingleThreadExecutor();
63 new CallableBackgroundInitializer<Integer>(null, exec);
6964 }
7065
7166 /**
7267 * Tests the implementation of initialize().
7368 */
69 @Test
7470 public void testInitialize() throws Exception {
75 TestCallable call = new TestCallable();
76 CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<Integer>(
71 final TestCallable call = new TestCallable();
72 final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<Integer>(
7773 call);
7874 assertEquals("Wrong result", RESULT, init.initialize());
7975 assertEquals("Wrong number of invocations", 1, call.callCount);
9086 /**
9187 * Records this invocation and returns the test result.
9288 */
89 @Override
9390 public Integer call() throws Exception {
9491 callCount++;
9592 return RESULT;
3434 /**
3535 * Test class for {@link ConcurrentUtils}.
3636 *
37 * @version $Id: ConcurrentUtilsTest.java 1153484 2011-08-03 13:39:42Z ggregory $
37 * @version $Id: ConcurrentUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3838 */
3939 public class ConcurrentUtilsTest {
4040 /**
107107 */
108108 @Test
109109 public void testExtractCauseError() {
110 Error err = new AssertionError("Test");
110 final Error err = new AssertionError("Test");
111111 try {
112112 ConcurrentUtils.extractCause(new ExecutionException(err));
113113 fail("Error not thrown!");
114 } catch (Error e) {
114 } catch (final Error e) {
115115 assertEquals("Wrong error", err, e);
116116 }
117117 }
121121 */
122122 @Test
123123 public void testExtractCauseUncheckedException() {
124 RuntimeException rex = new RuntimeException("Test");
124 final RuntimeException rex = new RuntimeException("Test");
125125 try {
126126 ConcurrentUtils.extractCause(new ExecutionException(rex));
127127 fail("Runtime exception not thrown!");
128 } catch (RuntimeException r) {
128 } catch (final RuntimeException r) {
129129 assertEquals("Wrong exception", rex, r);
130130 }
131131 }
135135 */
136136 @Test
137137 public void testExtractCauseChecked() {
138 Exception ex = new Exception("Test");
139 ConcurrentException cex = ConcurrentUtils
138 final Exception ex = new Exception("Test");
139 final ConcurrentException cex = ConcurrentUtils
140140 .extractCause(new ExecutionException(ex));
141141 assertSame("Wrong cause", ex, cex.getCause());
142142 }
163163 */
164164 @Test
165165 public void testExtractCauseUncheckedError() {
166 Error err = new AssertionError("Test");
166 final Error err = new AssertionError("Test");
167167 try {
168168 ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err));
169169 fail("Error not thrown!");
170 } catch (Error e) {
170 } catch (final Error e) {
171171 assertEquals("Wrong error", err, e);
172172 }
173173 }
177177 */
178178 @Test
179179 public void testExtractCauseUncheckedUncheckedException() {
180 RuntimeException rex = new RuntimeException("Test");
180 final RuntimeException rex = new RuntimeException("Test");
181181 try {
182182 ConcurrentUtils.extractCauseUnchecked(new ExecutionException(rex));
183183 fail("Runtime exception not thrown!");
184 } catch (RuntimeException r) {
184 } catch (final RuntimeException r) {
185185 assertEquals("Wrong exception", rex, r);
186186 }
187187 }
191191 */
192192 @Test
193193 public void testExtractCauseUncheckedChecked() {
194 Exception ex = new Exception("Test");
195 ConcurrentRuntimeException cex = ConcurrentUtils
194 final Exception ex = new Exception("Test");
195 final ConcurrentRuntimeException cex = ConcurrentUtils
196196 .extractCauseUnchecked(new ExecutionException(ex));
197197 assertSame("Wrong cause", ex, cex.getCause());
198198 }
202202 */
203203 @Test
204204 public void testHandleCauseError() throws ConcurrentException {
205 Error err = new AssertionError("Test");
205 final Error err = new AssertionError("Test");
206206 try {
207207 ConcurrentUtils.handleCause(new ExecutionException(err));
208208 fail("Error not thrown!");
209 } catch (Error e) {
209 } catch (final Error e) {
210210 assertEquals("Wrong error", err, e);
211211 }
212212 }
216216 */
217217 @Test
218218 public void testHandleCauseUncheckedException() throws ConcurrentException {
219 RuntimeException rex = new RuntimeException("Test");
219 final RuntimeException rex = new RuntimeException("Test");
220220 try {
221221 ConcurrentUtils.handleCause(new ExecutionException(rex));
222222 fail("Runtime exception not thrown!");
223 } catch (RuntimeException r) {
223 } catch (final RuntimeException r) {
224224 assertEquals("Wrong exception", rex, r);
225225 }
226226 }
230230 */
231231 @Test
232232 public void testHandleCauseChecked() {
233 Exception ex = new Exception("Test");
233 final Exception ex = new Exception("Test");
234234 try {
235235 ConcurrentUtils.handleCause(new ExecutionException(ex));
236236 fail("ConcurrentException not thrown!");
237 } catch (ConcurrentException cex) {
237 } catch (final ConcurrentException cex) {
238238 assertEquals("Wrong cause", ex, cex.getCause());
239239 }
240240 }
255255 */
256256 @Test
257257 public void testHandleCauseUncheckedError() {
258 Error err = new AssertionError("Test");
258 final Error err = new AssertionError("Test");
259259 try {
260260 ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err));
261261 fail("Error not thrown!");
262 } catch (Error e) {
262 } catch (final Error e) {
263263 assertEquals("Wrong error", err, e);
264264 }
265265 }
269269 */
270270 @Test
271271 public void testHandleCauseUncheckedUncheckedException() {
272 RuntimeException rex = new RuntimeException("Test");
272 final RuntimeException rex = new RuntimeException("Test");
273273 try {
274274 ConcurrentUtils.handleCauseUnchecked(new ExecutionException(rex));
275275 fail("Runtime exception not thrown!");
276 } catch (RuntimeException r) {
276 } catch (final RuntimeException r) {
277277 assertEquals("Wrong exception", rex, r);
278278 }
279279 }
283283 */
284284 @Test
285285 public void testHandleCauseUncheckedChecked() {
286 Exception ex = new Exception("Test");
286 final Exception ex = new Exception("Test");
287287 try {
288288 ConcurrentUtils.handleCauseUnchecked(new ExecutionException(ex));
289289 fail("ConcurrentRuntimeException not thrown!");
290 } catch (ConcurrentRuntimeException crex) {
290 } catch (final ConcurrentRuntimeException crex) {
291291 assertEquals("Wrong cause", ex, crex.getCause());
292292 }
293293 }
319319 @Test
320320 public void testInitialize() throws ConcurrentException {
321321 @SuppressWarnings("unchecked")
322 final
322323 ConcurrentInitializer<Object> init = EasyMock
323324 .createMock(ConcurrentInitializer.class);
324325 final Object result = new Object();
343344 @Test
344345 public void testInitializeUnchecked() throws ConcurrentException {
345346 @SuppressWarnings("unchecked")
347 final
346348 ConcurrentInitializer<Object> init = EasyMock
347349 .createMock(ConcurrentInitializer.class);
348350 final Object result = new Object();
359361 @Test
360362 public void testInitializeUncheckedEx() throws ConcurrentException {
361363 @SuppressWarnings("unchecked")
364 final
362365 ConcurrentInitializer<Object> init = EasyMock
363366 .createMock(ConcurrentInitializer.class);
364367 final Exception cause = new Exception();
367370 try {
368371 ConcurrentUtils.initializeUnchecked(init);
369372 fail("Exception not thrown!");
370 } catch (ConcurrentRuntimeException crex) {
373 } catch (final ConcurrentRuntimeException crex) {
371374 assertSame("Wrong cause", cause, crex.getCause());
372375 }
373376 EasyMock.verify(init);
379382 */
380383 @Test
381384 public void testConstantFuture_Integer() throws Exception {
382 Integer value = Integer.valueOf(5);
383 Future<Integer> test = ConcurrentUtils.constantFuture(value);
385 final Integer value = Integer.valueOf(5);
386 final Future<Integer> test = ConcurrentUtils.constantFuture(value);
384387 assertTrue(test.isDone());
385388 assertSame(value, test.get());
386389 assertSame(value, test.get(1000, TimeUnit.SECONDS));
395398 */
396399 @Test
397400 public void testConstantFuture_null() throws Exception {
398 Integer value = null;
399 Future<Integer> test = ConcurrentUtils.constantFuture(value);
401 final Integer value = null;
402 final Future<Integer> test = ConcurrentUtils.constantFuture(value);
400403 assertTrue(test.isDone());
401404 assertSame(value, test.get());
402405 assertSame(value, test.get(1000, TimeUnit.SECONDS));
414417 public void testPutIfAbsentKeyPresent() {
415418 final String key = "testKey";
416419 final Integer value = 42;
417 ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
420 final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
418421 map.put(key, value);
419422 assertEquals("Wrong result", value,
420423 ConcurrentUtils.putIfAbsent(map, key, 0));
428431 public void testPutIfAbsentKeyNotPresent() {
429432 final String key = "testKey";
430433 final Integer value = 42;
431 ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
434 final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
432435 assertEquals("Wrong result", value,
433436 ConcurrentUtils.putIfAbsent(map, key, value));
434437 assertEquals("Wrong value in map", value, map.get(key));
449452 @Test
450453 public void testCreateIfAbsentKeyPresent() throws ConcurrentException {
451454 @SuppressWarnings("unchecked")
455 final
452456 ConcurrentInitializer<Integer> init = EasyMock
453457 .createMock(ConcurrentInitializer.class);
454458 EasyMock.replay(init);
455459 final String key = "testKey";
456460 final Integer value = 42;
457 ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
461 final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
458462 map.put(key, value);
459463 assertEquals("Wrong result", value,
460464 ConcurrentUtils.createIfAbsent(map, key, init));
468472 @Test
469473 public void testCreateIfAbsentKeyNotPresent() throws ConcurrentException {
470474 @SuppressWarnings("unchecked")
475 final
471476 ConcurrentInitializer<Integer> init = EasyMock
472477 .createMock(ConcurrentInitializer.class);
473478 final String key = "testKey";
474479 final Integer value = 42;
475480 EasyMock.expect(init.get()).andReturn(value);
476481 EasyMock.replay(init);
477 ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
482 final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
478483 assertEquals("Wrong result", value,
479484 ConcurrentUtils.createIfAbsent(map, key, init));
480485 assertEquals("Wrong value in map", value, map.get(key));
487492 @Test
488493 public void testCreateIfAbsentNullMap() throws ConcurrentException {
489494 @SuppressWarnings("unchecked")
495 final
490496 ConcurrentInitializer<Integer> init = EasyMock
491497 .createMock(ConcurrentInitializer.class);
492498 EasyMock.replay(init);
500506 */
501507 @Test
502508 public void testCreateIfAbsentNullInit() throws ConcurrentException {
503 ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
509 final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
504510 final String key = "testKey";
505511 final Integer value = 42;
506512 map.put(key, value);
516522 public void testCreateIfAbsentUncheckedSuccess() {
517523 final String key = "testKey";
518524 final Integer value = 42;
519 ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
525 final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
520526 assertEquals("Wrong result", value,
521527 ConcurrentUtils.createIfAbsentUnchecked(map, key,
522528 new ConstantInitializer<Integer>(value)));
530536 public void testCreateIfAbsentUncheckedException()
531537 throws ConcurrentException {
532538 @SuppressWarnings("unchecked")
539 final
533540 ConcurrentInitializer<Integer> init = EasyMock
534541 .createMock(ConcurrentInitializer.class);
535 Exception ex = new Exception();
542 final Exception ex = new Exception();
536543 EasyMock.expect(init.get()).andThrow(new ConcurrentException(ex));
537544 EasyMock.replay(init);
538545 try {
539546 ConcurrentUtils.createIfAbsentUnchecked(
540547 new ConcurrentHashMap<String, Integer>(), "test", init);
541548 fail("Exception not thrown!");
542 } catch (ConcurrentRuntimeException crex) {
549 } catch (final ConcurrentRuntimeException crex) {
543550 assertEquals("Wrong cause", ex, crex.getCause());
544551 }
545552 EasyMock.verify(init);
2626 /**
2727 * Test class for {@code ConstantInitializer}.
2828 *
29 * @version $Id: ConstantInitializerTest.java 1153484 2011-08-03 13:39:42Z ggregory $
29 * @version $Id: ConstantInitializerTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3030 */
3131 public class ConstantInitializerTest {
3232 /** Constant for the object managed by the initializer. */
4646 * @param obj the object to compare with the test instance
4747 * @param expected the expected result
4848 */
49 private void checkEquals(Object obj, boolean expected) {
50 assertEquals("Wrong result of equals", expected, init.equals(obj));
49 private void checkEquals(final Object obj, final boolean expected) {
50 assertTrue("Wrong result of equals", expected == init.equals(obj));
5151 if (obj != null) {
52 assertEquals("Not symmetric", expected, obj.equals(init));
52 assertTrue("Not symmetric", expected == obj.equals(init));
5353 if (expected) {
5454 assertEquals("Different hash codes", init.hashCode(),
5555 obj.hashCode());
114114 */
115115 @Test
116116 public void testToString() {
117 String s = init.toString();
118 Pattern pattern = Pattern
117 final String s = init.toString();
118 final Pattern pattern = Pattern
119119 .compile("ConstantInitializer@\\d+ \\[ object = " + VALUE
120120 + " \\]");
121121 assertTrue("Wrong string: " + s, pattern.matcher(s).matches());
126126 */
127127 @Test
128128 public void testToStringNull() {
129 String s = new ConstantInitializer<Object>(null).toString();
129 final String s = new ConstantInitializer<Object>(null).toString();
130130 assertTrue("Object not found: " + s, s.indexOf("object = null") > 0);
131131 }
132132 }
3232 /**
3333 * Test class for {@link MultiBackgroundInitializer}.
3434 *
35 * @version $Id: MultiBackgroundInitializerTest.java 987621 2010-08-20 20:01:10Z oheger $
35 * @version $Id: MultiBackgroundInitializerTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3636 */
3737 public class MultiBackgroundInitializerTest {
3838 /** Constant for the names of the child initializers. */
5555 * not be checked)
5656 * @throws ConcurrentException if an error occurs
5757 */
58 private void checkChild(BackgroundInitializer<?> child,
59 ExecutorService expExec) throws ConcurrentException {
60 ChildBackgroundInitializer cinit = (ChildBackgroundInitializer) child;
61 Integer result = cinit.get();
58 private void checkChild(final BackgroundInitializer<?> child,
59 final ExecutorService expExec) throws ConcurrentException {
60 final ChildBackgroundInitializer cinit = (ChildBackgroundInitializer) child;
61 final Integer result = cinit.get();
6262 assertEquals("Wrong result", 1, result.intValue());
6363 assertEquals("Wrong number of executions", 1, cinit.initializeCalls);
6464 if (expExec != null) {
9191 @Test
9292 public void testInitializeNoChildren() throws ConcurrentException {
9393 assertTrue("Wrong result of start()", initializer.start());
94 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
94 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
9595 .get();
9696 assertTrue("Got child initializers", res.initializerNames().isEmpty());
9797 assertTrue("Executor not shutdown", initializer.getActiveExecutor()
112112 new ChildBackgroundInitializer());
113113 }
114114 initializer.start();
115 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
115 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
116116 .get();
117117 assertEquals("Wrong number of child initializers", count, res
118118 .initializerNames().size());
119119 for (int i = 0; i < count; i++) {
120 String key = CHILD_INIT + i;
120 final String key = CHILD_INIT + i;
121121 assertTrue("Name not found: " + key, res.initializerNames()
122122 .contains(key));
123123 assertEquals("Wrong result object", Integer.valueOf(1), res
144144 */
145145 @Test
146146 public void testInitializeExternalExec() throws ConcurrentException {
147 ExecutorService exec = Executors.newCachedThreadPool();
147 final ExecutorService exec = Executors.newCachedThreadPool();
148148 try {
149149 initializer = new MultiBackgroundInitializer(exec);
150150 checkInitialize();
163163 @Test
164164 public void testInitializeChildWithExecutor() throws ConcurrentException {
165165 final String initExec = "childInitializerWithExecutor";
166 ExecutorService exec = Executors.newSingleThreadExecutor();
166 final ExecutorService exec = Executors.newSingleThreadExecutor();
167167 try {
168 ChildBackgroundInitializer c1 = new ChildBackgroundInitializer();
169 ChildBackgroundInitializer c2 = new ChildBackgroundInitializer();
168 final ChildBackgroundInitializer c1 = new ChildBackgroundInitializer();
169 final ChildBackgroundInitializer c2 = new ChildBackgroundInitializer();
170170 c2.setExternalExecutor(exec);
171171 initializer.addInitializer(CHILD_INIT, c1);
172172 initializer.addInitializer(initExec, c2);
190190 initializer.addInitializer(CHILD_INIT,
191191 new ChildBackgroundInitializer());
192192 fail("Could add initializer after start()!");
193 } catch (IllegalStateException istex) {
193 } catch (final IllegalStateException istex) {
194194 initializer.get();
195195 }
196196 }
201201 */
202202 @Test(expected = NoSuchElementException.class)
203203 public void testResultGetInitializerUnknown() throws ConcurrentException {
204 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
204 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
205205 res.getInitializer("unknown");
206206 }
207207
211211 */
212212 @Test(expected = NoSuchElementException.class)
213213 public void testResultGetResultObjectUnknown() throws ConcurrentException {
214 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
214 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
215215 res.getResultObject("unknown");
216216 }
217217
221221 */
222222 @Test(expected = NoSuchElementException.class)
223223 public void testResultGetExceptionUnknown() throws ConcurrentException {
224 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
224 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
225225 res.getException("unknown");
226226 }
227227
231231 */
232232 @Test(expected = NoSuchElementException.class)
233233 public void testResultIsExceptionUnknown() throws ConcurrentException {
234 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
234 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
235235 res.isException("unknown");
236236 }
237237
241241 @Test(expected = UnsupportedOperationException.class)
242242 public void testResultInitializerNamesModify() throws ConcurrentException {
243243 checkInitialize();
244 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
245 .get();
246 Iterator<String> it = res.initializerNames().iterator();
244 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
245 .get();
246 final Iterator<String> it = res.initializerNames().iterator();
247247 it.next();
248248 it.remove();
249249 }
254254 */
255255 @Test
256256 public void testInitializeRuntimeEx() {
257 ChildBackgroundInitializer child = new ChildBackgroundInitializer();
257 final ChildBackgroundInitializer child = new ChildBackgroundInitializer();
258258 child.ex = new RuntimeException();
259259 initializer.addInitializer(CHILD_INIT, child);
260260 initializer.start();
261261 try {
262262 initializer.get();
263263 fail("Runtime exception not thrown!");
264 } catch (Exception ex) {
264 } catch (final Exception ex) {
265265 assertEquals("Wrong exception", child.ex, ex);
266266 }
267267 }
272272 */
273273 @Test
274274 public void testInitializeEx() throws ConcurrentException {
275 ChildBackgroundInitializer child = new ChildBackgroundInitializer();
275 final ChildBackgroundInitializer child = new ChildBackgroundInitializer();
276276 child.ex = new Exception();
277277 initializer.addInitializer(CHILD_INIT, child);
278278 initializer.start();
279 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
279 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
280280 .get();
281281 assertTrue("No exception flag", res.isException(CHILD_INIT));
282282 assertNull("Got a results object", res.getResultObject(CHILD_INIT));
283 ConcurrentException cex = res.getException(CHILD_INIT);
283 final ConcurrentException cex = res.getException(CHILD_INIT);
284284 assertEquals("Wrong cause", child.ex, cex.getCause());
285285 }
286286
291291 @Test
292292 public void testInitializeResultsIsSuccessfulTrue()
293293 throws ConcurrentException {
294 ChildBackgroundInitializer child = new ChildBackgroundInitializer();
294 final ChildBackgroundInitializer child = new ChildBackgroundInitializer();
295295 initializer.addInitializer(CHILD_INIT, child);
296296 initializer.start();
297 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
297 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
298298 .get();
299299 assertTrue("Wrong success flag", res.isSuccessful());
300300 }
306306 @Test
307307 public void testInitializeResultsIsSuccessfulFalse()
308308 throws ConcurrentException {
309 ChildBackgroundInitializer child = new ChildBackgroundInitializer();
309 final ChildBackgroundInitializer child = new ChildBackgroundInitializer();
310310 child.ex = new Exception();
311311 initializer.addInitializer(CHILD_INIT, child);
312312 initializer.start();
313 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
313 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
314314 .get();
315315 assertFalse("Wrong success flag", res.isSuccessful());
316316 }
324324 final String nameMulti = "multiChildInitializer";
325325 initializer
326326 .addInitializer(CHILD_INIT, new ChildBackgroundInitializer());
327 MultiBackgroundInitializer mi2 = new MultiBackgroundInitializer();
327 final MultiBackgroundInitializer mi2 = new MultiBackgroundInitializer();
328328 final int count = 3;
329329 for (int i = 0; i < count; i++) {
330330 mi2
333333 }
334334 initializer.addInitializer(nameMulti, mi2);
335335 initializer.start();
336 MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
337 .get();
338 ExecutorService exec = initializer.getActiveExecutor();
336 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
337 .get();
338 final ExecutorService exec = initializer.getActiveExecutor();
339339 checkChild(res.getInitializer(CHILD_INIT), exec);
340 MultiBackgroundInitializer.MultiBackgroundInitializerResults res2 = (MultiBackgroundInitializer.MultiBackgroundInitializerResults) res
340 final MultiBackgroundInitializer.MultiBackgroundInitializerResults res2 = (MultiBackgroundInitializer.MultiBackgroundInitializerResults) res
341341 .getResultObject(nameMulti);
342342 assertEquals("Wrong number of initializers", count, res2
343343 .initializerNames().size());
374374 throw ex;
375375 }
376376
377 return initializeCalls;
377 return Integer.valueOf(initializeCalls);
378378 }
379379 }
380380 }
3333 /**
3434 * Test class for TimedSemaphore.
3535 *
36 * @version $Id: TimedSemaphoreTest.java 1199894 2011-11-09 17:53:59Z ggregory $
36 * @version $Id: TimedSemaphoreTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3737 */
3838 public class TimedSemaphoreTest {
3939 /** Constant for the time period. */
5050 */
5151 @Test
5252 public void testInit() {
53 ScheduledExecutorService service = EasyMock
53 final ScheduledExecutorService service = EasyMock
5454 .createMock(ScheduledExecutorService.class);
5555 EasyMock.replay(service);
56 TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
56 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
5757 LIMIT);
5858 EasyMock.verify(service);
5959 assertEquals("Wrong service", service, semaphore.getExecutorService());
8282 */
8383 @Test
8484 public void testInitDefaultService() {
85 TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
86 ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore
85 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
86 final ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore
8787 .getExecutorService();
8888 assertFalse("Wrong periodic task policy", exec
8989 .getContinueExistingPeriodicTasksAfterShutdownPolicy());
9898 */
9999 @Test
100100 public void testStartTimer() throws InterruptedException {
101 TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD,
101 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD,
102102 UNIT, LIMIT);
103 ScheduledFuture<?> future = semaphore.startTimer();
103 final ScheduledFuture<?> future = semaphore.startTimer();
104104 assertNotNull("No future returned", future);
105105 Thread.sleep(PERIOD);
106106 final int trials = 10;
120120 */
121121 @Test
122122 public void testShutdownOwnExecutor() {
123 TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
123 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
124124 semaphore.shutdown();
125125 assertTrue("Not shutdown", semaphore.isShutdown());
126126 assertTrue("Executor not shutdown", semaphore.getExecutorService()
133133 */
134134 @Test
135135 public void testShutdownSharedExecutorNoTask() {
136 ScheduledExecutorService service = EasyMock
136 final ScheduledExecutorService service = EasyMock
137137 .createMock(ScheduledExecutorService.class);
138138 EasyMock.replay(service);
139 TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
139 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
140140 LIMIT);
141141 semaphore.shutdown();
142142 assertTrue("Not shutdown", semaphore.isShutdown());
149149 * @param service the mock
150150 * @param future the future
151151 */
152 private void prepareStartTimer(ScheduledExecutorService service,
153 ScheduledFuture<?> future) {
152 private void prepareStartTimer(final ScheduledExecutorService service,
153 final ScheduledFuture<?> future) {
154154 service.scheduleAtFixedRate((Runnable) EasyMock.anyObject(), EasyMock
155155 .eq(PERIOD), EasyMock.eq(PERIOD), EasyMock.eq(UNIT));
156156 EasyMock.expectLastCall().andReturn(future);
162162 */
163163 @Test
164164 public void testShutdownSharedExecutorTask() throws InterruptedException {
165 ScheduledExecutorService service = EasyMock
166 .createMock(ScheduledExecutorService.class);
167 ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
165 final ScheduledExecutorService service = EasyMock
166 .createMock(ScheduledExecutorService.class);
167 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
168168 prepareStartTimer(service, future);
169169 EasyMock.expect(Boolean.valueOf(future.cancel(false))).andReturn(Boolean.TRUE);
170170 EasyMock.replay(service, future);
171 TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
171 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
172172 PERIOD, UNIT, LIMIT);
173173 semaphore.acquire();
174174 semaphore.shutdown();
181181 */
182182 @Test
183183 public void testShutdownMultipleTimes() throws InterruptedException {
184 ScheduledExecutorService service = EasyMock
185 .createMock(ScheduledExecutorService.class);
186 ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
184 final ScheduledExecutorService service = EasyMock
185 .createMock(ScheduledExecutorService.class);
186 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
187187 prepareStartTimer(service, future);
188188 EasyMock.expect(Boolean.valueOf(future.cancel(false))).andReturn(Boolean.TRUE);
189189 EasyMock.replay(service, future);
190 TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
190 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
191191 PERIOD, UNIT, LIMIT);
192192 semaphore.acquire();
193193 for (int i = 0; i < 10; i++) {
201201 */
202202 @Test
203203 public void testAcquireLimit() throws InterruptedException {
204 ScheduledExecutorService service = EasyMock
205 .createMock(ScheduledExecutorService.class);
206 ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
204 final ScheduledExecutorService service = EasyMock
205 .createMock(ScheduledExecutorService.class);
206 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
207207 prepareStartTimer(service, future);
208208 EasyMock.replay(service, future);
209209 final int count = 10;
210 CountDownLatch latch = new CountDownLatch(count - 1);
211 TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, 1);
212 SemaphoreThread t = new SemaphoreThread(semaphore, latch, count,
210 final CountDownLatch latch = new CountDownLatch(count - 1);
211 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, 1);
212 final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count,
213213 count - 1);
214214 semaphore.setLimit(count - 1);
215215
238238 */
239239 @Test
240240 public void testAcquireMultipleThreads() throws InterruptedException {
241 ScheduledExecutorService service = EasyMock
242 .createMock(ScheduledExecutorService.class);
243 ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
244 prepareStartTimer(service, future);
245 EasyMock.replay(service, future);
246 TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
241 final ScheduledExecutorService service = EasyMock
242 .createMock(ScheduledExecutorService.class);
243 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
244 prepareStartTimer(service, future);
245 EasyMock.replay(service, future);
246 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
247247 PERIOD, UNIT, 1);
248248 semaphore.latch = new CountDownLatch(1);
249249 final int count = 10;
250 SemaphoreThread[] threads = new SemaphoreThread[count];
250 final SemaphoreThread[] threads = new SemaphoreThread[count];
251251 for (int i = 0; i < count; i++) {
252252 threads[i] = new SemaphoreThread(semaphore, null, 1, 0);
253253 threads[i].start();
273273 */
274274 @Test
275275 public void testAcquireNoLimit() throws InterruptedException {
276 ScheduledExecutorService service = EasyMock
277 .createMock(ScheduledExecutorService.class);
278 ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
279 prepareStartTimer(service, future);
280 EasyMock.replay(service, future);
281 TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
276 final ScheduledExecutorService service = EasyMock
277 .createMock(ScheduledExecutorService.class);
278 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
279 prepareStartTimer(service, future);
280 EasyMock.replay(service, future);
281 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
282282 PERIOD, UNIT, TimedSemaphore.NO_LIMIT);
283283 final int count = 1000;
284 CountDownLatch latch = new CountDownLatch(count);
285 SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
284 final CountDownLatch latch = new CountDownLatch(count);
285 final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
286286 t.start();
287287 latch.await();
288288 EasyMock.verify(service, future);
293293 */
294294 @Test(expected = IllegalStateException.class)
295295 public void testPassAfterShutdown() throws InterruptedException {
296 TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
296 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
297297 semaphore.shutdown();
298298 semaphore.acquire();
299299 }
307307 @Test
308308 public void testAcquireMultiplePeriods() throws InterruptedException {
309309 final int count = 1000;
310 TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(
310 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(
311311 PERIOD / 10, TimeUnit.MILLISECONDS, 1);
312312 semaphore.setLimit(count / 4);
313 CountDownLatch latch = new CountDownLatch(count);
314 SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
313 final CountDownLatch latch = new CountDownLatch(count);
314 final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
315315 t.start();
316316 latch.await();
317317 semaphore.shutdown();
323323 */
324324 @Test
325325 public void testGetAverageCallsPerPeriod() throws InterruptedException {
326 ScheduledExecutorService service = EasyMock
327 .createMock(ScheduledExecutorService.class);
328 ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
329 prepareStartTimer(service, future);
330 EasyMock.replay(service, future);
331 TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
326 final ScheduledExecutorService service = EasyMock
327 .createMock(ScheduledExecutorService.class);
328 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
329 prepareStartTimer(service, future);
330 EasyMock.replay(service, future);
331 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
332332 LIMIT);
333333 semaphore.acquire();
334334 semaphore.endOfPeriod();
347347 */
348348 @Test
349349 public void testGetAvailablePermits() throws InterruptedException {
350 ScheduledExecutorService service = EasyMock
351 .createMock(ScheduledExecutorService.class);
352 ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
353 prepareStartTimer(service, future);
354 EasyMock.replay(service, future);
355 TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
350 final ScheduledExecutorService service = EasyMock
351 .createMock(ScheduledExecutorService.class);
352 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
353 prepareStartTimer(service, future);
354 EasyMock.replay(service, future);
355 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
356356 LIMIT);
357357 for (int i = 0; i < LIMIT; i++) {
358358 assertEquals("Wrong available count at " + i, LIMIT - i, semaphore
379379 /** Counter for the endOfPeriod() invocations. */
380380 private int periodEnds;
381381
382 public TimedSemaphoreTestImpl(long timePeriod, TimeUnit timeUnit,
383 int limit) {
382 public TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit,
383 final int limit) {
384384 super(timePeriod, timeUnit, limit);
385385 }
386386
387 public TimedSemaphoreTestImpl(ScheduledExecutorService service,
388 long timePeriod, TimeUnit timeUnit, int limit) {
387 public TimedSemaphoreTestImpl(final ScheduledExecutorService service,
388 final long timePeriod, final TimeUnit timeUnit, final int limit) {
389389 super(service, timePeriod, timeUnit, limit);
390390 }
391391
404404 * Invokes the latch if one is set.
405405 */
406406 @Override
407 public void acquire() throws InterruptedException {
407 public synchronized void acquire() throws InterruptedException {
408408 super.acquire();
409409 if (latch != null) {
410410 latch.countDown();
415415 * Counts the number of invocations.
416416 */
417417 @Override
418 protected void endOfPeriod() {
418 protected synchronized void endOfPeriod() {
419419 super.endOfPeriod();
420 synchronized (this) {
421 periodEnds++;
422 }
420 periodEnds++;
423421 }
424422
425423 /**
449447 /** The number of invocations of the latch. */
450448 private final int latchCount;
451449
452 public SemaphoreThread(TimedSemaphore b, CountDownLatch l, int c, int lc) {
450 public SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc) {
453451 semaphore = b;
454452 latch = l;
455453 count = c;
471469 latch.countDown();
472470 }
473471 }
474 } catch (InterruptedException iex) {
472 } catch (final InterruptedException iex) {
475473 Thread.currentThread().interrupt();
476474 }
477475 }
1616
1717 package org.apache.commons.lang3.event;
1818
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertSame;
21
1922 import java.beans.PropertyChangeEvent;
2023 import java.beans.PropertyVetoException;
2124 import java.beans.VetoableChangeListener;
2932 import java.util.Date;
3033 import java.util.List;
3134
32 import junit.framework.TestCase;
33
3435 import org.easymock.EasyMock;
36 import org.junit.Test;
3537
3638 /**
3739 * @since 3.0
38 * @version $Id: EventListenerSupportTest.java 1144929 2011-07-10 18:26:16Z ggregory $
40 * @version $Id: EventListenerSupportTest.java 1553926 2013-12-28 21:15:10Z ggregory $
3941 */
40 public class EventListenerSupportTest extends TestCase
42 public class EventListenerSupportTest
4143 {
44 @Test(expected=NullPointerException.class)
4245 public void testAddNullListener()
4346 {
44 EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
45 try
46 {
47 listenerSupport.addListener(null);
48 fail("Should not be able to add a null listener.");
49 }
50 catch (NullPointerException e)
51 {
52
53 }
54 }
55
47 final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
48 listenerSupport.addListener(null);
49 }
50
51 @Test(expected=NullPointerException.class)
5652 public void testRemoveNullListener()
5753 {
58 EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
59 try
60 {
61 listenerSupport.removeListener(null);
62 fail("Should not be able to remove a null listener.");
63 }
64 catch (NullPointerException e)
65 {
66
67 }
68 }
69
54 final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
55 listenerSupport.removeListener(null);
56 }
57
58 @Test
7059 public void testEventDispatchOrder() throws PropertyVetoException
7160 {
72 EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
61 final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
7362 final List<VetoableChangeListener> calledListeners = new ArrayList<VetoableChangeListener>();
7463
7564 final VetoableChangeListener listener1 = createListener(calledListeners);
8271 assertSame(calledListeners.get(1), listener2);
8372 }
8473
74 @Test(expected=IllegalArgumentException.class)
8575 public void testCreateWithNonInterfaceParameter()
8676 {
87 try
88 {
89 EventListenerSupport.create(String.class);
90 fail("Should not be able to create using non-interface class.");
91 }
92 catch (IllegalArgumentException e)
93 {
94
95 }
96 }
97
77 EventListenerSupport.create(String.class);
78 }
79
80 @Test(expected=NullPointerException.class)
9881 public void testCreateWithNullParameter()
9982 {
100 try
101 {
102 EventListenerSupport.create(null);
103 fail("Should not be able to create using null class.");
104 }
105 catch (NullPointerException e)
106 {
107
108 }
109 }
110
83 EventListenerSupport.create(null);
84 }
85
86 @Test
11187 public void testRemoveListenerDuringEvent() throws PropertyVetoException
11288 {
11389 final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
12096 assertEquals(listenerSupport.getListenerCount(), 0);
12197 }
12298
99 @Test
123100 public void testGetListeners() {
124101 final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
125102
126 VetoableChangeListener[] listeners = listenerSupport.getListeners();
103 final VetoableChangeListener[] listeners = listenerSupport.getListeners();
127104 assertEquals(0, listeners.length);
128105 assertEquals(VetoableChangeListener.class, listeners.getClass().getComponentType());
129 VetoableChangeListener[] empty = listeners;
106 final VetoableChangeListener[] empty = listeners;
130107 //for fun, show that the same empty instance is used
131108 assertSame(empty, listenerSupport.getListeners());
132109
133 VetoableChangeListener listener1 = EasyMock.createNiceMock(VetoableChangeListener.class);
110 final VetoableChangeListener listener1 = EasyMock.createNiceMock(VetoableChangeListener.class);
134111 listenerSupport.addListener(listener1);
135112 assertEquals(1, listenerSupport.getListeners().length);
136 VetoableChangeListener listener2 = EasyMock.createNiceMock(VetoableChangeListener.class);
113 final VetoableChangeListener listener2 = EasyMock.createNiceMock(VetoableChangeListener.class);
137114 listenerSupport.addListener(listener2);
138115 assertEquals(2, listenerSupport.getListeners().length);
139116 listenerSupport.removeListener(listener1);
142119 assertSame(empty, listenerSupport.getListeners());
143120 }
144121
122 @Test
145123 public void testSerialization() throws IOException, ClassNotFoundException, PropertyVetoException {
146 EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
124 final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
147125 listenerSupport.addListener(new VetoableChangeListener() {
148126
149 public void vetoableChange(PropertyChangeEvent e) {
127 @Override
128 public void vetoableChange(final PropertyChangeEvent e) {
150129 }
151130 });
152131 listenerSupport.addListener(EasyMock.createNiceMock(VetoableChangeListener.class));
153132
154133 //serialize:
155 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
156 ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
134 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
135 final ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
157136
158137 objectOutputStream.writeObject(listenerSupport);
159138 objectOutputStream.close();
160139
161140 //deserialize:
162141 @SuppressWarnings("unchecked")
142 final
163143 EventListenerSupport<VetoableChangeListener> deserializedListenerSupport = (EventListenerSupport<VetoableChangeListener>) new ObjectInputStream(
164144 new ByteArrayInputStream(outputStream.toByteArray())).readObject();
165145
166146 //make sure we get a listener array back, of the correct component type, and that it contains only the serializable mock
167 VetoableChangeListener[] listeners = deserializedListenerSupport.getListeners();
147 final VetoableChangeListener[] listeners = deserializedListenerSupport.getListeners();
168148 assertEquals(VetoableChangeListener.class, listeners.getClass().getComponentType());
169149 assertEquals(1, listeners.length);
170150
171151 //now verify that the mock still receives events; we can infer that the proxy was correctly reconstituted
172 VetoableChangeListener listener = listeners[0];
173 PropertyChangeEvent evt = new PropertyChangeEvent(new Date(), "Day", 7, 9);
152 final VetoableChangeListener listener = listeners[0];
153 final PropertyChangeEvent evt = new PropertyChangeEvent(new Date(), "Day", 7, 9);
174154 listener.vetoableChange(evt);
175155 EasyMock.replay(listener);
176156 deserializedListenerSupport.fire().vetoableChange(evt);
181161 assertEquals(0, deserializedListenerSupport.getListeners().length);
182162 }
183163
164 @Test
184165 public void testSubclassInvocationHandling() throws PropertyVetoException {
185166
186167 @SuppressWarnings("serial")
168 final
187169 EventListenerSupport<VetoableChangeListener> eventListenerSupport = new EventListenerSupport<VetoableChangeListener>(
188170 VetoableChangeListener.class) {
171 private static final long serialVersionUID = 1L;
172
189173 @Override
190174 protected java.lang.reflect.InvocationHandler createInvocationHandler() {
191175 return new ProxyInvocationHandler() {
193177 * {@inheritDoc}
194178 */
195179 @Override
196 public Object invoke(Object proxy, Method method, Object[] args)
180 public Object invoke(final Object proxy, final Method method, final Object[] args)
197181 throws Throwable {
198182 return "vetoableChange".equals(method.getName())
199183 && "Hour".equals(((PropertyChangeEvent) args[0]).getPropertyName()) ? null
203187 }
204188 };
205189
206 VetoableChangeListener listener = EasyMock.createNiceMock(VetoableChangeListener.class);
190 final VetoableChangeListener listener = EasyMock.createNiceMock(VetoableChangeListener.class);
207191 eventListenerSupport.addListener(listener);
208 Object source = new Date();
209 PropertyChangeEvent ignore = new PropertyChangeEvent(source, "Hour", 5, 6);
210 PropertyChangeEvent respond = new PropertyChangeEvent(source, "Day", 6, 7);
192 final Object source = new Date();
193 final PropertyChangeEvent ignore = new PropertyChangeEvent(source, "Hour", 5, 6);
194 final PropertyChangeEvent respond = new PropertyChangeEvent(source, "Day", 6, 7);
211195 listener.vetoableChange(respond);
212196 EasyMock.replay(listener);
213197 eventListenerSupport.fire().vetoableChange(ignore);
219203 {
220204 listenerSupport.addListener(new VetoableChangeListener()
221205 {
222 public void vetoableChange(PropertyChangeEvent e)
206 @Override
207 public void vetoableChange(final PropertyChangeEvent e)
223208 {
224209 listenerSupport.removeListener(this);
225210 }
230215 {
231216 return new VetoableChangeListener()
232217 {
233 public void vetoableChange(PropertyChangeEvent e)
218 @Override
219 public void vetoableChange(final PropertyChangeEvent e)
234220 {
235221 calledListeners.add(this);
236222 }
1515 */
1616 package org.apache.commons.lang3.event;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertTrue;
22 import static org.junit.Assert.fail;
23
1824 import java.beans.PropertyChangeEvent;
1925 import java.beans.PropertyChangeListener;
2026 import java.beans.VetoableChangeListener;
2935
3036 import javax.naming.event.ObjectChangeListener;
3137
32 import junit.framework.TestCase;
38 import org.junit.Test;
3339
3440 /**
3541 * @since 3.0
36 * @version $Id: EventUtilsTest.java 1144929 2011-07-10 18:26:16Z ggregory $
42 * @version $Id: EventUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3743 */
38 public class EventUtilsTest extends TestCase
44 public class EventUtilsTest
3945 {
4046
47 @Test
4148 public void testConstructor() {
4249 assertNotNull(new EventUtils());
43 Constructor<?>[] cons = EventUtils.class.getDeclaredConstructors();
50 final Constructor<?>[] cons = EventUtils.class.getDeclaredConstructors();
4451 assertEquals(1, cons.length);
45 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
46 assertEquals(true, Modifier.isPublic(EventUtils.class.getModifiers()));
47 assertEquals(false, Modifier.isFinal(EventUtils.class.getModifiers()));
52 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
53 assertTrue(Modifier.isPublic(EventUtils.class.getModifiers()));
54 assertFalse(Modifier.isFinal(EventUtils.class.getModifiers()));
4855 }
4956
57 @Test
5058 public void testAddEventListener()
5159 {
5260 final PropertyChangeSource src = new PropertyChangeSource();
53 EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
54 PropertyChangeListener listener = handler.createListener(PropertyChangeListener.class);
61 final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
62 final PropertyChangeListener listener = handler.createListener(PropertyChangeListener.class);
5563 assertEquals(0, handler.getEventCount("propertyChange"));
5664 EventUtils.addEventListener(src, PropertyChangeListener.class, listener);
5765 assertEquals(0, handler.getEventCount("propertyChange"));
5967 assertEquals(1, handler.getEventCount("propertyChange"));
6068 }
6169
70 @Test
6271 public void testAddEventListenerWithNoAddMethod()
6372 {
6473 final PropertyChangeSource src = new PropertyChangeSource();
65 EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
66 ObjectChangeListener listener = handler.createListener(ObjectChangeListener.class);
74 final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
75 final ObjectChangeListener listener = handler.createListener(ObjectChangeListener.class);
6776 try
6877 {
6978 EventUtils.addEventListener(src, ObjectChangeListener.class, listener);
7079 fail("Should not be allowed to add a listener to an object that doesn't support it.");
7180 }
72 catch (IllegalArgumentException e)
81 catch (final IllegalArgumentException e)
7382 {
7483 assertEquals("Class " + src.getClass().getName() + " does not have a public add" + ObjectChangeListener.class.getSimpleName() + " method which takes a parameter of type " + ObjectChangeListener.class.getName() + ".", e.getMessage());
7584 }
7685 }
7786
87 @Test
7888 public void testAddEventListenerThrowsException()
7989 {
8090 final ExceptionEventSource src = new ExceptionEventSource();
8292 {
8393 EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener()
8494 {
85 public void propertyChange(PropertyChangeEvent e)
95 @Override
96 public void propertyChange(final PropertyChangeEvent e)
8697 {
8798 // Do nothing!
8899 }
89100 });
90101 fail("Add method should have thrown an exception, so method should fail.");
91102 }
92 catch (RuntimeException e)
93 {
94
95 }
96 }
97
103 catch (final RuntimeException e)
104 {
105
106 }
107 }
108
109 @Test
98110 public void testAddEventListenerWithPrivateAddMethod()
99111 {
100112 final PropertyChangeSource src = new PropertyChangeSource();
101 EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
102 VetoableChangeListener listener = handler.createListener(VetoableChangeListener.class);
113 final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
114 final VetoableChangeListener listener = handler.createListener(VetoableChangeListener.class);
103115 try
104116 {
105117 EventUtils.addEventListener(src, VetoableChangeListener.class, listener);
106118 fail("Should not be allowed to add a listener to an object that doesn't support it.");
107119 }
108 catch (IllegalArgumentException e)
120 catch (final IllegalArgumentException e)
109121 {
110122 assertEquals("Class " + src.getClass().getName() + " does not have a public add" + VetoableChangeListener.class.getSimpleName() + " method which takes a parameter of type " + VetoableChangeListener.class.getName() + ".", e.getMessage());
111123 }
112124 }
113125
126 @Test
114127 public void testBindEventsToMethod()
115128 {
116129 final PropertyChangeSource src = new PropertyChangeSource();
122135 }
123136
124137
138 @Test
125139 public void testBindEventsToMethodWithEvent()
126140 {
127141 final PropertyChangeSource src = new PropertyChangeSource();
133147 }
134148
135149
150 @Test
136151 public void testBindFilteredEventsToMethod()
137152 {
138153 final MultipleEventSource src = new MultipleEventSource();
171186 {
172187 private int count;
173188
174 public void eventOccurred(PropertyChangeEvent e)
189 public void eventOccurred(final PropertyChangeEvent e)
175190 {
176191 count++;
177192 }
185200
186201 private static class EventCountingInvociationHandler implements InvocationHandler
187202 {
188 private Map<String, Integer> eventCounts = new TreeMap<String, Integer>();
189
190 public <L> L createListener(Class<L> listenerType)
203 private final Map<String, Integer> eventCounts = new TreeMap<String, Integer>();
204
205 public <L> L createListener(final Class<L> listenerType)
191206 {
192207 return listenerType.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
193208 new Class[]{listenerType},
194209 this));
195210 }
196211
197 public int getEventCount(String eventName)
198 {
199 Integer count = eventCounts.get(eventName);
212 public int getEventCount(final String eventName)
213 {
214 final Integer count = eventCounts.get(eventName);
200215 return count == null ? 0 : count.intValue();
201216 }
202217
203 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
204 {
205 Integer count = eventCounts.get(method.getName());
218 @Override
219 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable
220 {
221 final Integer count = eventCounts.get(method.getName());
206222 if (count == null)
207223 {
208224 eventCounts.put(method.getName(), Integer.valueOf(1));
217233
218234 public static class MultipleEventSource
219235 {
220 private EventListenerSupport<MultipleEventListener> listeners = EventListenerSupport.create(MultipleEventListener.class);
221
222 public void addMultipleEventListener(MultipleEventListener listener)
236 private final EventListenerSupport<MultipleEventListener> listeners = EventListenerSupport.create(MultipleEventListener.class);
237
238 public void addMultipleEventListener(final MultipleEventListener listener)
223239 {
224240 listeners.addListener(listener);
225241 }
227243
228244 public static class ExceptionEventSource
229245 {
230 public void addPropertyChangeListener(PropertyChangeListener listener)
246 public void addPropertyChangeListener(final PropertyChangeListener listener)
231247 {
232248 throw new RuntimeException();
233249 }
235251
236252 public static class PropertyChangeSource
237253 {
238 private EventListenerSupport<PropertyChangeListener> listeners = EventListenerSupport.create(PropertyChangeListener.class);
254 private final EventListenerSupport<PropertyChangeListener> listeners = EventListenerSupport.create(PropertyChangeListener.class);
239255
240256 private String property;
241257
242 public void setProperty(String property)
243 {
244 String oldValue = this.property;
258 public void setProperty(final String property)
259 {
260 final String oldValue = this.property;
245261 this.property = property;
246262 listeners.fire().propertyChange(new PropertyChangeEvent(this, "property", oldValue, property));
247263 }
248264
249 protected void addVetoableChangeListener(VetoableChangeListener listener)
265 protected void addVetoableChangeListener(final VetoableChangeListener listener)
250266 {
251267 // Do nothing!
252268 }
253269
254 public void addPropertyChangeListener(PropertyChangeListener listener)
270 public void addPropertyChangeListener(final PropertyChangeListener listener)
255271 {
256272 listeners.addListener(listener);
257273 }
258274
259 public void removePropertyChangeListener(PropertyChangeListener listener)
275 public void removePropertyChangeListener(final PropertyChangeListener listener)
260276 {
261277 listeners.removeListener(listener);
262278 }
1515 */
1616 package org.apache.commons.lang3.exception;
1717
18 import org.junit.Test;
19 import org.junit.Before;
20 import static org.junit.Assert.*;
1821 import java.io.Serializable;
1922 import java.util.Arrays;
2023 import java.util.Collections;
2124 import java.util.Date;
2225 import java.util.List;
2326 import java.util.Set;
24
25 import junit.framework.TestCase;
2627
2728 import org.apache.commons.lang3.SerializationUtils;
2829 import org.apache.commons.lang3.tuple.Pair;
3132 /**
3233 * Abstract test of an ExceptionContext implementation.
3334 */
34 public abstract class AbstractExceptionContextTest<T extends ExceptionContext & Serializable> extends TestCase {
35 public abstract class AbstractExceptionContextTest<T extends ExceptionContext & Serializable> {
3536
3637 protected static final String TEST_MESSAGE_2 = "This is monotonous";
3738 protected static final String TEST_MESSAGE = "Test Message";
4445 }
4546 }
4647
47 @Override
48 protected void setUp() throws Exception {
48
49 @Before
50 public void setUp() throws Exception {
4951 exceptionContext
5052 .addContextValue("test1", null)
5153 .addContextValue("test2", "some value")
5456 .addContextValue("test Poorly written obj", new ObjectWithFaultyToString());
5557 }
5658
59 @Test
5760 public void testAddContextValue() {
58 String message = exceptionContext.getFormattedExceptionMessage(TEST_MESSAGE);
61 final String message = exceptionContext.getFormattedExceptionMessage(TEST_MESSAGE);
5962 assertTrue(message.indexOf(TEST_MESSAGE) >= 0);
6063 assertTrue(message.indexOf("test1") >= 0);
6164 assertTrue(message.indexOf("test2") >= 0);
7780 assertEquals(5, exceptionContext.getContextLabels().size());
7881 assertTrue(exceptionContext.getContextLabels().contains("test2"));
7982
80 String contextMessage = exceptionContext.getFormattedExceptionMessage(null);
83 final String contextMessage = exceptionContext.getFormattedExceptionMessage(null);
8184 assertTrue(contextMessage.indexOf(TEST_MESSAGE) == -1);
8285 }
8386
87 @Test
8488 public void testSetContextValue() {
8589 exceptionContext.addContextValue("test2", "different value");
8690 exceptionContext.setContextValue("test3", "3");
8791
88 String message = exceptionContext.getFormattedExceptionMessage(TEST_MESSAGE);
92 final String message = exceptionContext.getFormattedExceptionMessage(TEST_MESSAGE);
8993 assertTrue(message.indexOf(TEST_MESSAGE) >= 0);
9094 assertTrue(message.indexOf("test Poorly written obj") >= 0);
9195 assertTrue(message.indexOf("Crap") >= 0);
109113 assertEquals(6, exceptionContext.getContextEntries().size());
110114 assertEquals(6, exceptionContext.getContextLabels().size());
111115
112 String contextMessage = exceptionContext.getFormattedExceptionMessage(null);
116 final String contextMessage = exceptionContext.getFormattedExceptionMessage(null);
113117 assertTrue(contextMessage.indexOf(TEST_MESSAGE) == -1);
114118 }
115119
120 @Test
116121 public void testGetFirstContextValue() {
117122 exceptionContext.addContextValue("test2", "different value");
118123
125130 assertTrue(exceptionContext.getFirstContextValue("test2").equals("another"));
126131 }
127132
133 @Test
128134 public void testGetContextValues() {
129135 exceptionContext.addContextValue("test2", "different value");
130136
136142 assertTrue(exceptionContext.getFirstContextValue("test2").equals("another"));
137143 }
138144
145 @Test
139146 public void testGetContextLabels() {
140147 assertEquals(5, exceptionContext.getContextEntries().size());
141148
142149 exceptionContext.addContextValue("test2", "different value");
143150
144 Set<String> labels = exceptionContext.getContextLabels();
151 final Set<String> labels = exceptionContext.getContextLabels();
145152 assertEquals(6, exceptionContext.getContextEntries().size());
146153 assertEquals(5, labels.size());
147154 assertTrue(labels.contains("test1"));
150157 assertTrue(labels.contains("test Nbr"));
151158 }
152159
160 @Test
153161 public void testGetContextEntries() {
154162 assertEquals(5, exceptionContext.getContextEntries().size());
155163
156164 exceptionContext.addContextValue("test2", "different value");
157165
158 List<Pair<String, Object>> entries = exceptionContext.getContextEntries();
166 final List<Pair<String, Object>> entries = exceptionContext.getContextEntries();
159167 assertEquals(6, entries.size());
160168 assertEquals("test1", entries.get(0).getKey());
161169 assertEquals("test2", entries.get(1).getKey());
165173 assertEquals("test2", entries.get(5).getKey());
166174 }
167175
176 @Test
168177 public void testJavaSerialization() {
169178 exceptionContext.setContextValue("test Poorly written obj", "serializable replacement");
170179
171 @SuppressWarnings("unchecked")
172 T clone = (T)SerializationUtils.deserialize(SerializationUtils.serialize(exceptionContext));
180 final T clone = SerializationUtils.deserialize(SerializationUtils.serialize(exceptionContext));
173181 assertEquals(exceptionContext.getFormattedExceptionMessage(null), clone.getFormattedExceptionMessage(null));
174182 }
175183 }
1515 */
1616 package org.apache.commons.lang3.exception;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertNull;
20 import static org.junit.Assert.assertTrue;
21
1822 import java.util.Date;
1923
2024 import org.apache.commons.lang3.StringUtils;
25 import org.junit.Test;
2126
2227 /**
2328 * JUnit tests for ContextedException.
3035 super.setUp();
3136 }
3237
38 @Test
3339 public void testContextedException() {
3440 exceptionContext = new ContextedException();
35 String message = exceptionContext.getMessage();
36 String trace = ExceptionUtils.getStackTrace(exceptionContext);
41 final String message = exceptionContext.getMessage();
42 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
3743 assertTrue(trace.indexOf("ContextedException")>=0);
3844 assertTrue(StringUtils.isEmpty(message));
3945 }
4046
47 @Test
4148 public void testContextedExceptionString() {
4249 exceptionContext = new ContextedException(TEST_MESSAGE);
4350 assertEquals(TEST_MESSAGE, exceptionContext.getMessage());
4451
45 String trace = ExceptionUtils.getStackTrace(exceptionContext);
52 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
4653 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
4754 }
4855
56 @Test
4957 public void testContextedExceptionThrowable() {
5058 exceptionContext = new ContextedException(new Exception(TEST_MESSAGE));
51 String message = exceptionContext.getMessage();
52 String trace = ExceptionUtils.getStackTrace(exceptionContext);
59 final String message = exceptionContext.getMessage();
60 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
5361 assertTrue(trace.indexOf("ContextedException")>=0);
5462 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
5563 assertTrue(message.indexOf(TEST_MESSAGE)>=0);
5664 }
5765
66 @Test
5867 public void testContextedExceptionStringThrowable() {
5968 exceptionContext = new ContextedException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE));
60 String message = exceptionContext.getMessage();
61 String trace = ExceptionUtils.getStackTrace(exceptionContext);
69 final String message = exceptionContext.getMessage();
70 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
6271 assertTrue(trace.indexOf("ContextedException")>=0);
6372 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
6473 assertTrue(trace.indexOf(TEST_MESSAGE_2)>=0);
6574 assertTrue(message.indexOf(TEST_MESSAGE_2)>=0);
6675 }
6776
77 @Test
6878 public void testContextedExceptionStringThrowableContext() {
6979 exceptionContext = new ContextedException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE), new DefaultExceptionContext());
70 String message = exceptionContext.getMessage();
71 String trace = ExceptionUtils.getStackTrace(exceptionContext);
80 final String message = exceptionContext.getMessage();
81 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
7282 assertTrue(trace.indexOf("ContextedException")>=0);
7383 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
7484 assertTrue(trace.indexOf(TEST_MESSAGE_2)>=0);
7585 assertTrue(message.indexOf(TEST_MESSAGE_2)>=0);
7686 }
7787
88 @Test
7889 public void testNullExceptionPassing() {
7990 exceptionContext = new ContextedException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE), null)
8091 .addContextValue("test1", null)
8394 .addContextValue("test Nbr", Integer.valueOf(5))
8495 .addContextValue("test Poorly written obj", new ObjectWithFaultyToString());
8596
86 String message = exceptionContext.getMessage();
97 final String message = exceptionContext.getMessage();
8798 assertTrue(message != null);
8899 }
89100
101 @Test
90102 public void testRawMessage() {
91103 assertEquals(Exception.class.getName() + ": " + TEST_MESSAGE, exceptionContext.getRawMessage());
92104 exceptionContext = new ContextedException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE), new DefaultExceptionContext());
1515 */
1616 package org.apache.commons.lang3.exception;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertNull;
20 import static org.junit.Assert.assertTrue;
21
1822 import java.util.Date;
1923
2024 import org.apache.commons.lang3.StringUtils;
25 import org.junit.Before;
26 import org.junit.Test;
2127
2228 /**
2329 * JUnit tests for ContextedRuntimeException.
2531 public class ContextedRuntimeExceptionTest extends AbstractExceptionContextTest<ContextedRuntimeException> {
2632
2733 @Override
28 protected void setUp() throws Exception {
34 @Before
35 public void setUp() throws Exception {
2936 exceptionContext = new ContextedRuntimeException(new Exception(TEST_MESSAGE));
3037 super.setUp();
3138 }
3239
40 @Test
3341 public void testContextedException() {
3442 exceptionContext = new ContextedRuntimeException();
35 String message = exceptionContext.getMessage();
36 String trace = ExceptionUtils.getStackTrace(exceptionContext);
43 final String message = exceptionContext.getMessage();
44 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
3745 assertTrue(trace.indexOf("ContextedException")>=0);
3846 assertTrue(StringUtils.isEmpty(message));
3947 }
4048
49 @Test
4150 public void testContextedExceptionString() {
4251 exceptionContext = new ContextedRuntimeException(TEST_MESSAGE);
4352 assertEquals(TEST_MESSAGE, exceptionContext.getMessage());
4453
45 String trace = ExceptionUtils.getStackTrace(exceptionContext);
54 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
4655 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
4756 }
4857
58 @Test
4959 public void testContextedExceptionThrowable() {
5060 exceptionContext = new ContextedRuntimeException(new Exception(TEST_MESSAGE));
51 String message = exceptionContext.getMessage();
52 String trace = ExceptionUtils.getStackTrace(exceptionContext);
61 final String message = exceptionContext.getMessage();
62 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
5363 assertTrue(trace.indexOf("ContextedException")>=0);
5464 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
5565 assertTrue(message.indexOf(TEST_MESSAGE)>=0);
5666 }
5767
68 @Test
5869 public void testContextedExceptionStringThrowable() {
5970 exceptionContext = new ContextedRuntimeException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE));
60 String message = exceptionContext.getMessage();
61 String trace = ExceptionUtils.getStackTrace(exceptionContext);
71 final String message = exceptionContext.getMessage();
72 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
6273 assertTrue(trace.indexOf("ContextedException")>=0);
6374 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
6475 assertTrue(trace.indexOf(TEST_MESSAGE_2)>=0);
6576 assertTrue(message.indexOf(TEST_MESSAGE_2)>=0);
6677 }
6778
79 @Test
6880 public void testContextedExceptionStringThrowableContext() {
69 exceptionContext = new ContextedRuntimeException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE), new DefaultExceptionContext() {});
70 String message = exceptionContext.getMessage();
71 String trace = ExceptionUtils.getStackTrace(exceptionContext);
81 // Use an anonymous subclass to make sure users can provide custom implementations
82 exceptionContext = new ContextedRuntimeException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE),
83 new DefaultExceptionContext() {private static final long serialVersionUID = 1L;});
84 final String message = exceptionContext.getMessage();
85 final String trace = ExceptionUtils.getStackTrace(exceptionContext);
7286 assertTrue(trace.indexOf("ContextedException")>=0);
7387 assertTrue(trace.indexOf(TEST_MESSAGE)>=0);
7488 assertTrue(trace.indexOf(TEST_MESSAGE_2)>=0);
7589 assertTrue(message.indexOf(TEST_MESSAGE_2)>=0);
7690 }
7791
92 @Test
7893 public void testNullExceptionPassing() {
7994 exceptionContext = new ContextedRuntimeException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE), null)
8095 .addContextValue("test1", null)
8398 .addContextValue("test Nbr", Integer.valueOf(5))
8499 .addContextValue("test Poorly written obj", new ObjectWithFaultyToString());
85100
86 String message = exceptionContext.getMessage();
101 final String message = exceptionContext.getMessage();
87102 assertTrue(message != null);
88103 }
89104
105 @Test
90106 public void testRawMessage() {
91107 assertEquals(Exception.class.getName() + ": " + TEST_MESSAGE, exceptionContext.getRawMessage());
92108 exceptionContext = new ContextedRuntimeException(TEST_MESSAGE_2, new Exception(TEST_MESSAGE), new DefaultExceptionContext());
1515 */
1616 package org.apache.commons.lang3.exception;
1717
18 import org.junit.Before;
19 import org.junit.Test;
20
1821 /**
1922 * JUnit tests for DefaultExceptionContext.
2023 *
2225 public class DefaultExceptionContextTest extends AbstractExceptionContextTest<DefaultExceptionContext> {
2326
2427 @Override
28 @Before
2529 public void setUp() throws Exception {
2630 exceptionContext = new DefaultExceptionContext();
2731 super.setUp();
2832 }
2933
34 @Test
3035 public void testFormattedExceptionMessageNull() {
3136 exceptionContext = new DefaultExceptionContext();
3237 exceptionContext.getFormattedExceptionMessage(null);
1515 */
1616 package org.apache.commons.lang3.exception;
1717
18 import org.junit.After;
19 import org.junit.Test;
20 import org.junit.Before;
21 import static org.junit.Assert.*;
1822 import java.io.ByteArrayOutputStream;
1923 import java.io.PrintStream;
2024 import java.io.PrintWriter;
2226 import java.lang.reflect.Constructor;
2327 import java.lang.reflect.Modifier;
2428 import java.util.List;
25
26 import junit.framework.TestCase;
2729
2830 /**
2931 * Tests {@link org.apache.commons.lang3.exception.ExceptionUtils}.
4648 *
4749 * @since 1.0
4850 */
49 public class ExceptionUtilsTest extends TestCase {
51 public class ExceptionUtilsTest {
5052
5153 private NestableException nested;
5254 private Throwable withCause;
5456 private Throwable jdkNoCause;
5557 private ExceptionWithCause cyclicCause;
5658
57 public ExceptionUtilsTest(String name) {
58 super(name);
59 }
60
61 @Override
59
60 @Before
6261 public void setUp() {
6362 withoutCause = createExceptionWithoutCause();
6463 nested = new NestableException(withoutCause);
6564 withCause = new ExceptionWithCause(nested);
6665 jdkNoCause = new NullPointerException();
67 ExceptionWithCause a = new ExceptionWithCause(null);
68 ExceptionWithCause b = new ExceptionWithCause(a);
66 final ExceptionWithCause a = new ExceptionWithCause(null);
67 final ExceptionWithCause b = new ExceptionWithCause(a);
6968 a.setCause(b);
7069 cyclicCause = new ExceptionWithCause(a);
7170 }
7271
73 @Override
74 protected void tearDown() throws Exception {
72
73 @After
74 public void tearDown() throws Exception {
7575 withoutCause = null;
7676 nested = null;
7777 withCause = null;
8383 private Throwable createExceptionWithoutCause() {
8484 try {
8585 throw new ExceptionWithoutCause();
86 } catch (Throwable t) {
86 } catch (final Throwable t) {
8787 return t;
8888 }
8989 }
9292 try {
9393 try {
9494 throw new ExceptionWithCause(createExceptionWithoutCause());
95 } catch (Throwable t) {
95 } catch (final Throwable t) {
9696 throw new ExceptionWithCause(t);
9797 }
98 } catch (Throwable t) {
98 } catch (final Throwable t) {
9999 return t;
100100 }
101101 }
102102
103103 //-----------------------------------------------------------------------
104104
105 @Test
105106 public void testConstructor() {
106107 assertNotNull(new ExceptionUtils());
107 Constructor<?>[] cons = ExceptionUtils.class.getDeclaredConstructors();
108 final Constructor<?>[] cons = ExceptionUtils.class.getDeclaredConstructors();
108109 assertEquals(1, cons.length);
109 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
110 assertEquals(true, Modifier.isPublic(ExceptionUtils.class.getModifiers()));
111 assertEquals(false, Modifier.isFinal(ExceptionUtils.class.getModifiers()));
110 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
111 assertTrue(Modifier.isPublic(ExceptionUtils.class.getModifiers()));
112 assertFalse(Modifier.isFinal(ExceptionUtils.class.getModifiers()));
112113 }
113114
114115 //-----------------------------------------------------------------------
115116 @SuppressWarnings("deprecation") // Specifically tests the deprecated methods
117 @Test
116118 public void testGetCause_Throwable() {
117119 assertSame(null, ExceptionUtils.getCause(null));
118120 assertSame(null, ExceptionUtils.getCause(withoutCause));
125127 }
126128
127129 @SuppressWarnings("deprecation") // Specifically tests the deprecated methods
130 @Test
128131 public void testGetCause_ThrowableArray() {
129132 assertSame(null, ExceptionUtils.getCause(null, null));
130133 assertSame(null, ExceptionUtils.getCause(null, new String[0]));
143146 assertSame(null, ExceptionUtils.getCause(withoutCause, new String[] {"getTargetException"}));
144147 }
145148
149 @Test
146150 public void testGetRootCause_Throwable() {
147151 assertSame(null, ExceptionUtils.getRootCause(null));
148152 assertSame(null, ExceptionUtils.getRootCause(withoutCause));
153157 }
154158
155159 //-----------------------------------------------------------------------
160 @Test
156161 public void testGetThrowableCount_Throwable() {
157162 assertEquals(0, ExceptionUtils.getThrowableCount(null));
158163 assertEquals(1, ExceptionUtils.getThrowableCount(withoutCause));
163168 }
164169
165170 //-----------------------------------------------------------------------
171 @Test
166172 public void testGetThrowables_Throwable_null() {
167173 assertEquals(0, ExceptionUtils.getThrowables(null).length);
168174 }
169175
176 @Test
170177 public void testGetThrowables_Throwable_withoutCause() {
171 Throwable[] throwables = ExceptionUtils.getThrowables(withoutCause);
178 final Throwable[] throwables = ExceptionUtils.getThrowables(withoutCause);
172179 assertEquals(1, throwables.length);
173180 assertSame(withoutCause, throwables[0]);
174181 }
175182
183 @Test
176184 public void testGetThrowables_Throwable_nested() {
177 Throwable[] throwables = ExceptionUtils.getThrowables(nested);
185 final Throwable[] throwables = ExceptionUtils.getThrowables(nested);
178186 assertEquals(2, throwables.length);
179187 assertSame(nested, throwables[0]);
180188 assertSame(withoutCause, throwables[1]);
181189 }
182190
191 @Test
183192 public void testGetThrowables_Throwable_withCause() {
184 Throwable[] throwables = ExceptionUtils.getThrowables(withCause);
193 final Throwable[] throwables = ExceptionUtils.getThrowables(withCause);
185194 assertEquals(3, throwables.length);
186195 assertSame(withCause, throwables[0]);
187196 assertSame(nested, throwables[1]);
188197 assertSame(withoutCause, throwables[2]);
189198 }
190199
200 @Test
191201 public void testGetThrowables_Throwable_jdkNoCause() {
192 Throwable[] throwables = ExceptionUtils.getThrowables(jdkNoCause);
202 final Throwable[] throwables = ExceptionUtils.getThrowables(jdkNoCause);
193203 assertEquals(1, throwables.length);
194204 assertSame(jdkNoCause, throwables[0]);
195205 }
196206
207 @Test
197208 public void testGetThrowables_Throwable_recursiveCause() {
198 Throwable[] throwables = ExceptionUtils.getThrowables(cyclicCause);
209 final Throwable[] throwables = ExceptionUtils.getThrowables(cyclicCause);
199210 assertEquals(3, throwables.length);
200211 assertSame(cyclicCause, throwables[0]);
201212 assertSame(cyclicCause.getCause(), throwables[1]);
203214 }
204215
205216 //-----------------------------------------------------------------------
217 @Test
206218 public void testGetThrowableList_Throwable_null() {
207 List<?> throwables = ExceptionUtils.getThrowableList(null);
219 final List<?> throwables = ExceptionUtils.getThrowableList(null);
208220 assertEquals(0, throwables.size());
209221 }
210222
223 @Test
211224 public void testGetThrowableList_Throwable_withoutCause() {
212 List<?> throwables = ExceptionUtils.getThrowableList(withoutCause);
225 final List<?> throwables = ExceptionUtils.getThrowableList(withoutCause);
213226 assertEquals(1, throwables.size());
214227 assertSame(withoutCause, throwables.get(0));
215228 }
216229
230 @Test
217231 public void testGetThrowableList_Throwable_nested() {
218 List<?> throwables = ExceptionUtils.getThrowableList(nested);
232 final List<?> throwables = ExceptionUtils.getThrowableList(nested);
219233 assertEquals(2, throwables.size());
220234 assertSame(nested, throwables.get(0));
221235 assertSame(withoutCause, throwables.get(1));
222236 }
223237
238 @Test
224239 public void testGetThrowableList_Throwable_withCause() {
225 List<?> throwables = ExceptionUtils.getThrowableList(withCause);
240 final List<?> throwables = ExceptionUtils.getThrowableList(withCause);
226241 assertEquals(3, throwables.size());
227242 assertSame(withCause, throwables.get(0));
228243 assertSame(nested, throwables.get(1));
229244 assertSame(withoutCause, throwables.get(2));
230245 }
231246
247 @Test
232248 public void testGetThrowableList_Throwable_jdkNoCause() {
233 List<?> throwables = ExceptionUtils.getThrowableList(jdkNoCause);
249 final List<?> throwables = ExceptionUtils.getThrowableList(jdkNoCause);
234250 assertEquals(1, throwables.size());
235251 assertSame(jdkNoCause, throwables.get(0));
236252 }
237253
254 @Test
238255 public void testGetThrowableList_Throwable_recursiveCause() {
239 List<?> throwables = ExceptionUtils.getThrowableList(cyclicCause);
256 final List<?> throwables = ExceptionUtils.getThrowableList(cyclicCause);
240257 assertEquals(3, throwables.size());
241258 assertSame(cyclicCause, throwables.get(0));
242259 assertSame(cyclicCause.getCause(), throwables.get(1));
244261 }
245262
246263 //-----------------------------------------------------------------------
264 @Test
247265 public void testIndexOf_ThrowableClass() {
248266 assertEquals(-1, ExceptionUtils.indexOfThrowable(null, null));
249267 assertEquals(-1, ExceptionUtils.indexOfThrowable(null, NestableException.class));
266284 assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, Exception.class));
267285 }
268286
287 @Test
269288 public void testIndexOf_ThrowableClassInt() {
270289 assertEquals(-1, ExceptionUtils.indexOfThrowable(null, null, 0));
271290 assertEquals(-1, ExceptionUtils.indexOfThrowable(null, NestableException.class, 0));
294313 }
295314
296315 //-----------------------------------------------------------------------
316 @Test
297317 public void testIndexOfType_ThrowableClass() {
298318 assertEquals(-1, ExceptionUtils.indexOfType(null, null));
299319 assertEquals(-1, ExceptionUtils.indexOfType(null, NestableException.class));
316336 assertEquals(0, ExceptionUtils.indexOfType(withCause, Exception.class));
317337 }
318338
339 @Test
319340 public void testIndexOfType_ThrowableClassInt() {
320341 assertEquals(-1, ExceptionUtils.indexOfType(null, null, 0));
321342 assertEquals(-1, ExceptionUtils.indexOfType(null, NestableException.class, 0));
344365 }
345366
346367 //-----------------------------------------------------------------------
368 @Test
347369 public void testPrintRootCauseStackTrace_Throwable() throws Exception {
348370 ExceptionUtils.printRootCauseStackTrace(null);
349371 // could pipe system.err to a known stream, but not much point as
350372 // internally this method calls stram method anyway
351373 }
352374
375 @Test
353376 public void testPrintRootCauseStackTrace_ThrowableStream() throws Exception {
354377 ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
355378 ExceptionUtils.printRootCauseStackTrace(null, (PrintStream) null);
360383 try {
361384 ExceptionUtils.printRootCauseStackTrace(withCause, (PrintStream) null);
362385 fail();
363 } catch (IllegalArgumentException ex) {
386 } catch (final IllegalArgumentException ex) {
364387 }
365388
366389 out = new ByteArrayOutputStream(1024);
367 Throwable withCause = createExceptionWithCause();
368 ExceptionUtils.printRootCauseStackTrace(withCause, new PrintStream(out));
390 final Throwable cause = createExceptionWithCause();
391 ExceptionUtils.printRootCauseStackTrace(cause, new PrintStream(out));
369392 String stackTrace = out.toString();
370393 assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) != -1);
371394
375398 assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) == -1);
376399 }
377400
401 @Test
378402 public void testPrintRootCauseStackTrace_ThrowableWriter() throws Exception {
379403 StringWriter writer = new StringWriter(1024);
380404 ExceptionUtils.printRootCauseStackTrace(null, (PrintWriter) null);
385409 try {
386410 ExceptionUtils.printRootCauseStackTrace(withCause, (PrintWriter) null);
387411 fail();
388 } catch (IllegalArgumentException ex) {
412 } catch (final IllegalArgumentException ex) {
389413 }
390414
391415 writer = new StringWriter(1024);
392 Throwable withCause = createExceptionWithCause();
393 ExceptionUtils.printRootCauseStackTrace(withCause, new PrintWriter(writer));
416 final Throwable cause = createExceptionWithCause();
417 ExceptionUtils.printRootCauseStackTrace(cause, new PrintWriter(writer));
394418 String stackTrace = writer.toString();
395419 assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) != -1);
396420
401425 }
402426
403427 //-----------------------------------------------------------------------
428 @Test
404429 public void testGetRootCauseStackTrace_Throwable() throws Exception {
405430 assertEquals(0, ExceptionUtils.getRootCauseStackTrace(null).length);
406431
407 Throwable withCause = createExceptionWithCause();
408 String[] stackTrace = ExceptionUtils.getRootCauseStackTrace(withCause);
432 final Throwable cause = createExceptionWithCause();
433 String[] stackTrace = ExceptionUtils.getRootCauseStackTrace(cause);
409434 boolean match = false;
410 for (String element : stackTrace) {
435 for (final String element : stackTrace) {
411436 if (element.startsWith(ExceptionUtils.WRAPPED_MARKER)) {
412437 match = true;
413438 break;
414439 }
415440 }
416 assertEquals(true, match);
441 assertTrue(match);
417442
418443 stackTrace = ExceptionUtils.getRootCauseStackTrace(withoutCause);
419444 match = false;
420 for (String element : stackTrace) {
445 for (final String element : stackTrace) {
421446 if (element.startsWith(ExceptionUtils.WRAPPED_MARKER)) {
422447 match = true;
423448 break;
424449 }
425450 }
426 assertEquals(false, match);
427 }
428
451 assertFalse(match);
452 }
453
454 @Test(expected=IllegalArgumentException.class)
429455 public void testRemoveCommonFrames_ListList() throws Exception {
430 try {
431 ExceptionUtils.removeCommonFrames(null, null);
432 fail();
433 } catch (IllegalArgumentException ex) {
434 }
435 }
436
456 ExceptionUtils.removeCommonFrames(null, null);
457 }
458
459 @Test
437460 public void test_getMessage_Throwable() {
438461 Throwable th = null;
439462 assertEquals("", ExceptionUtils.getMessage(th));
445468 assertEquals("ExceptionUtilsTest.ExceptionWithCause: Wrapper", ExceptionUtils.getMessage(th));
446469 }
447470
471 @Test
448472 public void test_getRootCauseMessage_Throwable() {
449473 Throwable th = null;
450474 assertEquals("", ExceptionUtils.getRootCauseMessage(th));
463487 * of <code>Throwable</code>.
464488 */
465489 private static class ExceptionWithCause extends Exception {
490 private static final long serialVersionUID = 1L;
491
466492 private Throwable cause;
467493
468 public ExceptionWithCause(String str, Throwable cause) {
494 public ExceptionWithCause(final String str, final Throwable cause) {
469495 super(str);
470496 setCause(cause);
471497 }
472498
473 public ExceptionWithCause(Throwable cause) {
499 public ExceptionWithCause(final Throwable cause) {
474500 super();
475501 setCause(cause);
476502 }
480506 return cause;
481507 }
482508
483 public void setCause(Throwable cause) {
509 public void setCause(final Throwable cause) {
484510 this.cause = cause;
485511 }
486512 }
491517 * return value of <code>Throwable</code>.
492518 */
493519 private static class ExceptionWithoutCause extends Exception {
494 @SuppressWarnings("unused")
520 private static final long serialVersionUID = 1L;
521
522 @SuppressWarnings("unused")
495523 public void getTargetException() {
496524 }
497525 }
499527 // Temporary classes to allow the nested exception code to be removed
500528 // prior to a rewrite of this test class.
501529 private static class NestableException extends Exception {
530 private static final long serialVersionUID = 1L;
531
502532 @SuppressWarnings("unused")
503533 public NestableException() { super(); }
504 public NestableException(Throwable t) { super(t); }
534 public NestableException(final Throwable t) { super(t); }
505535 }
506536
507537 }
1717 */
1818 package org.apache.commons.lang3.math;
1919
20 import junit.framework.TestCase;
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertSame;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
26 import org.junit.Test;
2127
2228 /**
2329 * Test cases for the {@link Fraction} class
2430 *
25 * @version $Id: FractionTest.java 1153484 2011-08-03 13:39:42Z ggregory $
31 * @version $Id: FractionTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2632 */
27 public class FractionTest extends TestCase {
33 public class FractionTest {
2834
2935 private static final int SKIP = 500; //53
3036
31 public FractionTest(String name) {
32 super(name);
33 }
34
3537 //--------------------------------------------------------------------------
36
38 @Test
3739 public void testConstants() {
3840 assertEquals(0, Fraction.ZERO.getNumerator());
3941 assertEquals(1, Fraction.ZERO.getDenominator());
7274 assertEquals(5, Fraction.FOUR_FIFTHS.getDenominator());
7375 }
7476
77 @Test
7578 public void testFactory_int_int() {
7679 Fraction f = null;
7780
119122 try {
120123 f = Fraction.getFraction(1, 0);
121124 fail("expecting ArithmeticException");
122 } catch (ArithmeticException ex) {}
125 } catch (final ArithmeticException ex) {}
123126
124127 try {
125128 f = Fraction.getFraction(2, 0);
126129 fail("expecting ArithmeticException");
127 } catch (ArithmeticException ex) {}
130 } catch (final ArithmeticException ex) {}
128131
129132 try {
130133 f = Fraction.getFraction(-3, 0);
131134 fail("expecting ArithmeticException");
132 } catch (ArithmeticException ex) {}
135 } catch (final ArithmeticException ex) {}
133136
134137 // very large: can't represent as unsimplified fraction, although
135138 try {
136139 f = Fraction.getFraction(4, Integer.MIN_VALUE);
137140 fail("expecting ArithmeticException");
138 } catch (ArithmeticException ex) {}
141 } catch (final ArithmeticException ex) {}
139142 try {
140143 f = Fraction.getFraction(1, Integer.MIN_VALUE);
141144 fail("expecting ArithmeticException");
142 } catch (ArithmeticException ex) {}
143 }
144
145 } catch (final ArithmeticException ex) {}
146 }
147
148 @Test
145149 public void testFactory_int_int_int() {
146150 Fraction f = null;
147151
167171 try {
168172 f = Fraction.getFraction(1, -6, -10);
169173 fail("expecting ArithmeticException");
170 } catch (ArithmeticException ex) {}
174 } catch (final ArithmeticException ex) {}
171175
172176 try {
173177 f = Fraction.getFraction(1, -6, -10);
174178 fail("expecting ArithmeticException");
175 } catch (ArithmeticException ex) {}
179 } catch (final ArithmeticException ex) {}
176180
177181 try {
178182 f = Fraction.getFraction(1, -6, -10);
179183 fail("expecting ArithmeticException");
180 } catch (ArithmeticException ex) {}
184 } catch (final ArithmeticException ex) {}
181185
182186 // negative whole
183187 f = Fraction.getFraction(-1, 6, 10);
187191 try {
188192 f = Fraction.getFraction(-1, -6, 10);
189193 fail("expecting ArithmeticException");
190 } catch (ArithmeticException ex) {}
194 } catch (final ArithmeticException ex) {}
191195
192196 try {
193197 f = Fraction.getFraction(-1, 6, -10);
194198 fail("expecting ArithmeticException");
195 } catch (ArithmeticException ex) {}
199 } catch (final ArithmeticException ex) {}
196200
197201 try {
198202 f = Fraction.getFraction(-1, -6, -10);
199203 fail("expecting ArithmeticException");
200 } catch (ArithmeticException ex) {}
204 } catch (final ArithmeticException ex) {}
201205
202206 // zero denominator
203207 try {
204208 f = Fraction.getFraction(0, 1, 0);
205209 fail("expecting ArithmeticException");
206 } catch (ArithmeticException ex) {}
210 } catch (final ArithmeticException ex) {}
207211
208212 try {
209213 f = Fraction.getFraction(1, 2, 0);
210214 fail("expecting ArithmeticException");
211 } catch (ArithmeticException ex) {}
215 } catch (final ArithmeticException ex) {}
212216
213217 try {
214218 f = Fraction.getFraction(-1, -3, 0);
215219 fail("expecting ArithmeticException");
216 } catch (ArithmeticException ex) {}
220 } catch (final ArithmeticException ex) {}
217221
218222 try {
219223 f = Fraction.getFraction(Integer.MAX_VALUE, 1, 2);
220224 fail("expecting ArithmeticException");
221 } catch (ArithmeticException ex) {}
225 } catch (final ArithmeticException ex) {}
222226
223227 try {
224228 f = Fraction.getFraction(-Integer.MAX_VALUE, 1, 2);
225229 fail("expecting ArithmeticException");
226 } catch (ArithmeticException ex) {}
230 } catch (final ArithmeticException ex) {}
227231
228232 // very large
229233 f = Fraction.getFraction(-1, 0, Integer.MAX_VALUE);
234238 // negative denominators not allowed in this constructor.
235239 f = Fraction.getFraction(0, 4, Integer.MIN_VALUE);
236240 fail("expecting ArithmeticException");
237 } catch (ArithmeticException ex) {}
241 } catch (final ArithmeticException ex) {}
238242 try {
239243 f = Fraction.getFraction(1, 1, Integer.MAX_VALUE);
240244 fail("expecting ArithmeticException");
241 } catch (ArithmeticException ex) {}
245 } catch (final ArithmeticException ex) {}
242246 try {
243247 f = Fraction.getFraction(-1, 2, Integer.MAX_VALUE);
244248 fail("expecting ArithmeticException");
245 } catch (ArithmeticException ex) {}
246 }
249 } catch (final ArithmeticException ex) {}
250 }
251 @Test
247252 public void testReducedFactory_int_int() {
248253 Fraction f = null;
249254
283288 try {
284289 f = Fraction.getReducedFraction(1, 0);
285290 fail("expecting ArithmeticException");
286 } catch (ArithmeticException ex) {}
291 } catch (final ArithmeticException ex) {}
287292
288293 try {
289294 f = Fraction.getReducedFraction(2, 0);
290295 fail("expecting ArithmeticException");
291 } catch (ArithmeticException ex) {}
296 } catch (final ArithmeticException ex) {}
292297
293298 try {
294299 f = Fraction.getReducedFraction(-3, 0);
295300 fail("expecting ArithmeticException");
296 } catch (ArithmeticException ex) {}
301 } catch (final ArithmeticException ex) {}
297302
298303 // reduced
299304 f = Fraction.getReducedFraction(0, 2);
326331 try {
327332 f = Fraction.getReducedFraction(-7, Integer.MIN_VALUE);
328333 fail("Expecting ArithmeticException");
329 } catch (ArithmeticException ex) {}
334 } catch (final ArithmeticException ex) {}
330335
331336 // LANG-662
332337 f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2);
334339 assertEquals(1, f.getDenominator());
335340 }
336341
342 @Test
337343 public void testFactory_double() {
338344 Fraction f = null;
339345
340346 try {
341347 f = Fraction.getFraction(Double.NaN);
342348 fail("expecting ArithmeticException");
343 } catch (ArithmeticException ex) {}
349 } catch (final ArithmeticException ex) {}
344350
345351 try {
346352 f = Fraction.getFraction(Double.POSITIVE_INFINITY);
347353 fail("expecting ArithmeticException");
348 } catch (ArithmeticException ex) {}
354 } catch (final ArithmeticException ex) {}
349355
350356 try {
351357 f = Fraction.getFraction(Double.NEGATIVE_INFINITY);
352358 fail("expecting ArithmeticException");
353 } catch (ArithmeticException ex) {}
359 } catch (final ArithmeticException ex) {}
354360
355361 try {
356362 f = Fraction.getFraction((double) Integer.MAX_VALUE + 1);
357363 fail("expecting ArithmeticException");
358 } catch (ArithmeticException ex) {}
364 } catch (final ArithmeticException ex) {}
359365
360366 // zero
361367 f = Fraction.getFraction(0.0d);
398404 for (int j = 1; j <= i; j++) { // numerator
399405 try {
400406 f = Fraction.getFraction((double) j / (double) i);
401 } catch (ArithmeticException ex) {
407 } catch (final ArithmeticException ex) {
402408 System.err.println(j + " " + i);
403409 throw ex;
404410 }
412418 for (int j = 1; j <= i; j++) { // numerator
413419 try {
414420 f = Fraction.getFraction((double) j / (double) i);
415 } catch (ArithmeticException ex) {
421 } catch (final ArithmeticException ex) {
416422 System.err.println(j + " " + i);
417423 throw ex;
418424 }
423429 }
424430 }
425431
432 @Test(expected=IllegalArgumentException.class)
426433 public void testFactory_String() {
427 try {
428 Fraction.getFraction(null);
429 fail("expecting IllegalArgumentException");
430 } catch (IllegalArgumentException ex) {}
434 Fraction.getFraction(null);
431435 }
432436
433437
438 @Test
434439 public void testFactory_String_double() {
435440 Fraction f = null;
436441
453458 try {
454459 f = Fraction.getFraction("2.3R");
455460 fail("Expecting NumberFormatException");
456 } catch (NumberFormatException ex) {}
461 } catch (final NumberFormatException ex) {}
457462
458463 try {
459464 f = Fraction.getFraction("2147483648"); // too big
460465 fail("Expecting NumberFormatException");
461 } catch (NumberFormatException ex) {}
466 } catch (final NumberFormatException ex) {}
462467
463468 try {
464469 f = Fraction.getFraction(".");
465470 fail("Expecting NumberFormatException");
466 } catch (NumberFormatException ex) {}
467 }
468
471 } catch (final NumberFormatException ex) {}
472 }
473
474 @Test
469475 public void testFactory_String_proper() {
470476 Fraction f = null;
471477
496502 try {
497503 f = Fraction.getFraction("2 3");
498504 fail("expecting NumberFormatException");
499 } catch (NumberFormatException ex) {}
505 } catch (final NumberFormatException ex) {}
500506
501507 try {
502508 f = Fraction.getFraction("a 3");
503509 fail("expecting NumberFormatException");
504 } catch (NumberFormatException ex) {}
510 } catch (final NumberFormatException ex) {}
505511
506512 try {
507513 f = Fraction.getFraction("2 b/4");
508514 fail("expecting NumberFormatException");
509 } catch (NumberFormatException ex) {}
515 } catch (final NumberFormatException ex) {}
510516
511517 try {
512518 f = Fraction.getFraction("2 ");
513519 fail("expecting NumberFormatException");
514 } catch (NumberFormatException ex) {}
520 } catch (final NumberFormatException ex) {}
515521
516522 try {
517523 f = Fraction.getFraction(" 3");
518524 fail("expecting NumberFormatException");
519 } catch (NumberFormatException ex) {}
525 } catch (final NumberFormatException ex) {}
520526
521527 try {
522528 f = Fraction.getFraction(" ");
523529 fail("expecting NumberFormatException");
524 } catch (NumberFormatException ex) {}
525 }
526
530 } catch (final NumberFormatException ex) {}
531 }
532
533 @Test
527534 public void testFactory_String_improper() {
528535 Fraction f = null;
529536
554561 try {
555562 f = Fraction.getFraction("2/d");
556563 fail("expecting NumberFormatException");
557 } catch (NumberFormatException ex) {}
564 } catch (final NumberFormatException ex) {}
558565
559566 try {
560567 f = Fraction.getFraction("2e/3");
561568 fail("expecting NumberFormatException");
562 } catch (NumberFormatException ex) {}
569 } catch (final NumberFormatException ex) {}
563570
564571 try {
565572 f = Fraction.getFraction("2/");
566573 fail("expecting NumberFormatException");
567 } catch (NumberFormatException ex) {}
574 } catch (final NumberFormatException ex) {}
568575
569576 try {
570577 f = Fraction.getFraction("/");
571578 fail("expecting NumberFormatException");
572 } catch (NumberFormatException ex) {}
573 }
574
579 } catch (final NumberFormatException ex) {}
580 }
581
582 @Test
575583 public void testGets() {
576584 Fraction f = null;
577585
594602 assertEquals(1, f.getDenominator());
595603 }
596604
605 @Test
597606 public void testConversions() {
598607 Fraction f = null;
599608
604613 assertEquals(3.875d, f.doubleValue(), 0.00001d);
605614 }
606615
616 @Test
607617 public void testReduce() {
608618 Fraction f = null;
609619
652662 assertEquals(1, result.getDenominator());
653663 }
654664
665 @Test
655666 public void testInvert() {
656667 Fraction f = null;
657668
674685 try {
675686 f = f.invert();
676687 fail("expecting ArithmeticException");
677 } catch (ArithmeticException ex) {}
688 } catch (final ArithmeticException ex) {}
678689
679690 // large values
680691 f = Fraction.getFraction(Integer.MIN_VALUE, 1);
681692 try {
682693 f = f.invert();
683694 fail("expecting ArithmeticException");
684 } catch (ArithmeticException ex) {}
695 } catch (final ArithmeticException ex) {}
685696
686697 f = Fraction.getFraction(Integer.MAX_VALUE, 1);
687698 f = f.invert();
689700 assertEquals(Integer.MAX_VALUE, f.getDenominator());
690701 }
691702
703 @Test
692704 public void testNegate() {
693705 Fraction f = null;
694706
712724 try {
713725 f = f.negate();
714726 fail("expecting ArithmeticException");
715 } catch (ArithmeticException ex) {}
727 } catch (final ArithmeticException ex) {}
716728 }
717729
730 @Test
718731 public void testAbs() {
719732 Fraction f = null;
720733
742755 try {
743756 f = f.abs();
744757 fail("expecting ArithmeticException");
745 } catch (ArithmeticException ex) {}
758 } catch (final ArithmeticException ex) {}
746759 }
747760
761 @Test
748762 public void testPow() {
749763 Fraction f = null;
750764
818832 try {
819833 f = f.pow(-1);
820834 fail("expecting ArithmeticException");
821 } catch (ArithmeticException ex) {}
835 } catch (final ArithmeticException ex) {}
822836 try {
823837 f = f.pow(Integer.MIN_VALUE);
824838 fail("expecting ArithmeticException");
825 } catch (ArithmeticException ex) {}
839 } catch (final ArithmeticException ex) {}
826840
827841 // one to any power is still one.
828842 f = Fraction.getFraction(1, 1);
841855 try {
842856 f = f.pow(2);
843857 fail("expecting ArithmeticException");
844 } catch (ArithmeticException ex) {}
858 } catch (final ArithmeticException ex) {}
845859
846860 // Numerator growing too negative during the pow operation.
847861 f = Fraction.getFraction(Integer.MIN_VALUE, 1);
848862 try {
849863 f = f.pow(3);
850864 fail("expecting ArithmeticException");
851 } catch (ArithmeticException ex) {}
865 } catch (final ArithmeticException ex) {}
852866
853867 f = Fraction.getFraction(65536, 1);
854868 try {
855869 f = f.pow(2);
856870 fail("expecting ArithmeticException");
857 } catch (ArithmeticException ex) {}
871 } catch (final ArithmeticException ex) {}
858872 }
859873
874 @Test
860875 public void testAdd() {
861876 Fraction f = null;
862877 Fraction f1 = null;
920935 try {
921936 f.add(null);
922937 fail("expecting IllegalArgumentException");
923 } catch (IllegalArgumentException ex) {}
938 } catch (final IllegalArgumentException ex) {}
924939
925940 // if this fraction is added naively, it will overflow.
926941 // check that it doesn't.
945960 try {
946961 f = f.add(Fraction.ONE); // should overflow
947962 fail("expecting ArithmeticException but got: " + f.toString());
948 } catch (ArithmeticException ex) {}
963 } catch (final ArithmeticException ex) {}
949964
950965 // denominator should not be a multiple of 2 or 3 to trigger overflow
951966 f1 = Fraction.getFraction(Integer.MIN_VALUE, 5);
953968 try {
954969 f = f1.add(f2); // should overflow
955970 fail("expecting ArithmeticException but got: " + f.toString());
956 } catch (ArithmeticException ex) {}
971 } catch (final ArithmeticException ex) {}
957972
958973 try {
959974 f= Fraction.getFraction(-Integer.MAX_VALUE, 1);
960975 f = f.add(f);
961976 fail("expecting ArithmeticException");
962 } catch (ArithmeticException ex) {}
977 } catch (final ArithmeticException ex) {}
963978
964979 try {
965980 f= Fraction.getFraction(-Integer.MAX_VALUE, 1);
966981 f = f.add(f);
967982 fail("expecting ArithmeticException");
968 } catch (ArithmeticException ex) {}
983 } catch (final ArithmeticException ex) {}
969984
970985 f1 = Fraction.getFraction(3,327680);
971986 f2 = Fraction.getFraction(2,59049);
972987 try {
973988 f = f1.add(f2); // should overflow
974989 fail("expecting ArithmeticException but got: " + f.toString());
975 } catch (ArithmeticException ex) {}
990 } catch (final ArithmeticException ex) {}
976991 }
977992
993 @Test
978994 public void testSubtract() {
979995 Fraction f = null;
980996 Fraction f1 = null;
10301046 try {
10311047 f.subtract(null);
10321048 fail("expecting IllegalArgumentException");
1033 } catch (IllegalArgumentException ex) {}
1049 } catch (final IllegalArgumentException ex) {}
10341050
10351051 // if this fraction is subtracted naively, it will overflow.
10361052 // check that it doesn't.
10571073 f2 = Fraction.getFraction(1, Integer.MAX_VALUE - 1);
10581074 f = f1.subtract(f2);
10591075 fail("expecting ArithmeticException"); //should overflow
1060 } catch (ArithmeticException ex) {}
1076 } catch (final ArithmeticException ex) {}
10611077
10621078 // denominator should not be a multiple of 2 or 3 to trigger overflow
10631079 f1 = Fraction.getFraction(Integer.MIN_VALUE, 5);
10651081 try {
10661082 f = f1.subtract(f2); // should overflow
10671083 fail("expecting ArithmeticException but got: " + f.toString());
1068 } catch (ArithmeticException ex) {}
1084 } catch (final ArithmeticException ex) {}
10691085
10701086 try {
10711087 f= Fraction.getFraction(Integer.MIN_VALUE, 1);
10721088 f = f.subtract(Fraction.ONE);
10731089 fail("expecting ArithmeticException");
1074 } catch (ArithmeticException ex) {}
1090 } catch (final ArithmeticException ex) {}
10751091
10761092 try {
10771093 f= Fraction.getFraction(Integer.MAX_VALUE, 1);
10781094 f = f.subtract(Fraction.ONE.negate());
10791095 fail("expecting ArithmeticException");
1080 } catch (ArithmeticException ex) {}
1096 } catch (final ArithmeticException ex) {}
10811097
10821098 f1 = Fraction.getFraction(3,327680);
10831099 f2 = Fraction.getFraction(2,59049);
10841100 try {
10851101 f = f1.subtract(f2); // should overflow
10861102 fail("expecting ArithmeticException but got: " + f.toString());
1087 } catch (ArithmeticException ex) {}
1103 } catch (final ArithmeticException ex) {}
10881104 }
10891105
1106 @Test
10901107 public void testMultiply() {
10911108 Fraction f = null;
10921109 Fraction f1 = null;
11401157 try {
11411158 f.multiplyBy(null);
11421159 fail("expecting IllegalArgumentException");
1143 } catch (IllegalArgumentException ex) {}
1160 } catch (final IllegalArgumentException ex) {}
11441161
11451162 try {
11461163 f1 = Fraction.getFraction(1, Integer.MAX_VALUE);
11471164 f = f1.multiplyBy(f1); // should overflow
11481165 fail("expecting ArithmeticException");
1149 } catch (ArithmeticException ex) {}
1166 } catch (final ArithmeticException ex) {}
11501167
11511168 try {
11521169 f1 = Fraction.getFraction(1, -Integer.MAX_VALUE);
11531170 f = f1.multiplyBy(f1); // should overflow
11541171 fail("expecting ArithmeticException");
1155 } catch (ArithmeticException ex) {}
1172 } catch (final ArithmeticException ex) {}
11561173 }
11571174
1175 @Test
11581176 public void testDivide() {
11591177 Fraction f = null;
11601178 Fraction f1 = null;
11711189 try {
11721190 f = f1.divideBy(f2);
11731191 fail("expecting ArithmeticException");
1174 } catch (ArithmeticException ex) {}
1192 } catch (final ArithmeticException ex) {}
11751193
11761194 f1 = Fraction.getFraction(0, 5);
11771195 f2 = Fraction.getFraction(2, 7);
11981216 try {
11991217 f.divideBy(null);
12001218 fail("IllegalArgumentException");
1201 } catch (IllegalArgumentException ex) {}
1219 } catch (final IllegalArgumentException ex) {}
12021220
12031221 try {
12041222 f1 = Fraction.getFraction(1, Integer.MAX_VALUE);
12051223 f = f1.divideBy(f1.invert()); // should overflow
12061224 fail("expecting ArithmeticException");
1207 } catch (ArithmeticException ex) {}
1225 } catch (final ArithmeticException ex) {}
12081226 try {
12091227 f1 = Fraction.getFraction(1, -Integer.MAX_VALUE);
12101228 f = f1.divideBy(f1.invert()); // should overflow
12111229 fail("expecting ArithmeticException");
1212 } catch (ArithmeticException ex) {}
1230 } catch (final ArithmeticException ex) {}
12131231 }
12141232
1233 @Test
12151234 public void testEquals() {
12161235 Fraction f1 = null;
12171236 Fraction f2 = null;
12181237
12191238 f1 = Fraction.getFraction(3, 5);
1220 assertEquals(false, f1.equals(null));
1221 assertEquals(false, f1.equals(new Object()));
1222 assertEquals(false, f1.equals(Integer.valueOf(6)));
1239 assertFalse(f1.equals(null));
1240 assertFalse(f1.equals(new Object()));
1241 assertFalse(f1.equals(Integer.valueOf(6)));
12231242
12241243 f1 = Fraction.getFraction(3, 5);
12251244 f2 = Fraction.getFraction(2, 5);
1226 assertEquals(false, f1.equals(f2));
1227 assertEquals(true, f1.equals(f1));
1228 assertEquals(true, f2.equals(f2));
1245 assertFalse(f1.equals(f2));
1246 assertTrue(f1.equals(f1));
1247 assertTrue(f2.equals(f2));
12291248
12301249 f2 = Fraction.getFraction(3, 5);
1231 assertEquals(true, f1.equals(f2));
1250 assertTrue(f1.equals(f2));
12321251
12331252 f2 = Fraction.getFraction(6, 10);
1234 assertEquals(false, f1.equals(f2));
1253 assertFalse(f1.equals(f2));
12351254 }
12361255
1256 @Test
12371257 public void testHashCode() {
1238 Fraction f1 = Fraction.getFraction(3, 5);
1258 final Fraction f1 = Fraction.getFraction(3, 5);
12391259 Fraction f2 = Fraction.getFraction(3, 5);
12401260
12411261 assertTrue(f1.hashCode() == f2.hashCode());
12471267 assertTrue(f1.hashCode() != f2.hashCode());
12481268 }
12491269
1270 @Test
12501271 public void testCompareTo() {
12511272 Fraction f1 = null;
12521273 Fraction f2 = null;
12571278 try {
12581279 f1.compareTo(null);
12591280 fail("expecting NullPointerException");
1260 } catch (NullPointerException ex) {}
1281 } catch (final NullPointerException ex) {}
12611282
12621283 f2 = Fraction.getFraction(2, 5);
12631284 assertTrue(f1.compareTo(f2) > 0);
12811302
12821303 }
12831304
1305 @Test
12841306 public void testToString() {
12851307 Fraction f = null;
12861308
12871309 f = Fraction.getFraction(3, 5);
1288 String str = f.toString();
1310 final String str = f.toString();
12891311 assertEquals("3/5", str);
12901312 assertSame(str, f.toString());
12911313
13081330 assertEquals("-2147483648/2147483647", f.toString());
13091331 }
13101332
1333 @Test
13111334 public void testToProperString() {
13121335 Fraction f = null;
13131336
13141337 f = Fraction.getFraction(3, 5);
1315 String str = f.toProperString();
1338 final String str = f.toProperString();
13161339 assertEquals("3/5", str);
13171340 assertSame(str, f.toProperString());
13181341
1515 */
1616 package org.apache.commons.lang3.math;
1717
18 import junit.framework.TestCase;
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertTrue;
20 import static org.junit.Assert.fail;
21
22 import org.junit.Test;
1923
2024 /**
2125 * Unit tests {@link org.apache.commons.lang3.math.IEEE754rUtils}.
2226 *
23 * @version $Id: IEEE754rUtilsTest.java 889219 2009-12-10 12:02:50Z bayard $
27 * @version $Id: IEEE754rUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2428 */
25 public class IEEE754rUtilsTest extends TestCase {
29 public class IEEE754rUtilsTest {
2630
31 @Test
2732 public void testLang381() {
2833 assertEquals(1.2, IEEE754rUtils.min(1.2, 2.5, Double.NaN), 0.01);
2934 assertEquals(2.5, IEEE754rUtils.max(1.2, 2.5, Double.NaN), 0.01);
3237 assertEquals(2.5f, IEEE754rUtils.max(1.2f, 2.5f, Float.NaN), 0.01);
3338 assertTrue(Float.isNaN(IEEE754rUtils.max(Float.NaN, Float.NaN, Float.NaN)));
3439
35 double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
40 final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
3641 assertEquals(42.0, IEEE754rUtils.max(a), 0.01);
3742 assertEquals(1.2, IEEE754rUtils.min(a), 0.01);
3843
39 double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
44 final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
4045 assertEquals(42.0, IEEE754rUtils.max(b), 0.01);
4146 assertEquals(1.2, IEEE754rUtils.min(b), 0.01);
4247
43 float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
48 final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
4449 assertEquals(1.2f, IEEE754rUtils.min(aF), 0.01);
4550 assertEquals(42.0f, IEEE754rUtils.max(aF), 0.01);
4651
47 float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
52 final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
4853 assertEquals(1.2f, IEEE754rUtils.min(bF), 0.01);
4954 assertEquals(42.0f, IEEE754rUtils.max(bF), 0.01);
5055 }
5156
57 @Test
5258 public void testEnforceExceptions() {
5359 try {
5460 IEEE754rUtils.min( (float[]) null);
5561 fail("IllegalArgumentException expected for null input");
56 } catch(IllegalArgumentException iae) { /* expected */ }
62 } catch(final IllegalArgumentException iae) { /* expected */ }
5763
5864 try {
5965 IEEE754rUtils.min(new float[0]);
6066 fail("IllegalArgumentException expected for empty input");
61 } catch(IllegalArgumentException iae) { /* expected */ }
67 } catch(final IllegalArgumentException iae) { /* expected */ }
6268
6369 try {
6470 IEEE754rUtils.max( (float[]) null);
6571 fail("IllegalArgumentException expected for null input");
66 } catch(IllegalArgumentException iae) { /* expected */ }
72 } catch(final IllegalArgumentException iae) { /* expected */ }
6773
6874 try {
6975 IEEE754rUtils.max(new float[0]);
7076 fail("IllegalArgumentException expected for empty input");
71 } catch(IllegalArgumentException iae) { /* expected */ }
77 } catch(final IllegalArgumentException iae) { /* expected */ }
7278
7379 try {
7480 IEEE754rUtils.min( (double[]) null);
7581 fail("IllegalArgumentException expected for null input");
76 } catch(IllegalArgumentException iae) { /* expected */ }
82 } catch(final IllegalArgumentException iae) { /* expected */ }
7783
7884 try {
7985 IEEE754rUtils.min(new double[0]);
8086 fail("IllegalArgumentException expected for empty input");
81 } catch(IllegalArgumentException iae) { /* expected */ }
87 } catch(final IllegalArgumentException iae) { /* expected */ }
8288
8389 try {
8490 IEEE754rUtils.max( (double[]) null);
8591 fail("IllegalArgumentException expected for null input");
86 } catch(IllegalArgumentException iae) { /* expected */ }
92 } catch(final IllegalArgumentException iae) { /* expected */ }
8793
8894 try {
8995 IEEE754rUtils.max(new double[0]);
9096 fail("IllegalArgumentException expected for empty input");
91 } catch(IllegalArgumentException iae) { /* expected */ }
97 } catch(final IllegalArgumentException iae) { /* expected */ }
9298
9399 }
94100
101 @Test
95102 public void testConstructorExists() {
96103 new IEEE754rUtils();
97104 }
1515 */
1616 package org.apache.commons.lang3.math;
1717
18 import static org.apache.commons.lang3.JavaVersion.JAVA_1_3;
19 import static org.junit.Assert.*;
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertTrue;
22 import static org.junit.Assert.fail;
2023
2124 import java.lang.reflect.Constructor;
2225 import java.lang.reflect.Modifier;
2326 import java.math.BigDecimal;
2427 import java.math.BigInteger;
2528
26 import org.apache.commons.lang3.SystemUtils;
27
2829 import org.junit.Test;
2930
3031 /**
3132 * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}.
3233 *
33 * @version $Id: NumberUtilsTest.java 1160660 2011-08-23 12:32:52Z sebb $
34 * @version $Id: NumberUtilsTest.java 1544776 2013-11-23 12:25:48Z sebb $
3435 */
3536 public class NumberUtilsTest {
3637
3839 @Test
3940 public void testConstructor() {
4041 assertNotNull(new NumberUtils());
41 Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors();
42 final Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors();
4243 assertEquals(1, cons.length);
4344 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
4445 assertTrue(Modifier.isPublic(NumberUtils.class.getModifiers()));
113114 assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f);
114115 assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f);
115116 }
116
117
118 /**
119 * Test for {(@link NumberUtils#createNumber(String)}
120 */
121 @Test
122 public void testStringCreateNumberEnsureNoPrecisionLoss(){
123 String shouldBeFloat = "1.23";
124 String shouldBeDouble = "3.40282354e+38";
125 String shouldBeBigDecimal = "1.797693134862315759e+308";
126
127 assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float);
128 assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double);
129 assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal);
130 }
117131 /**
118132 * Test for {@link NumberUtils#toDouble(String)}.
119133 */
204218 assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils
205219 .createNumber("12345678901234567890L"));
206220
207 // jdk 1.2 doesn't support this. unsure about jdk 1.2.2
208 if (SystemUtils.isJavaVersionAtLeast(JAVA_1_3)) {
209 assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils
221 assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils
210222 .createNumber("1.1E-700F"));
211 }
223
212224 assertEquals("createNumber(String) 16 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils
213225 .createNumber("10" + Integer.MAX_VALUE + "L"));
214226 assertEquals("createNumber(String) 17 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils
225237 // LANG-693
226238 assertEquals("createNumber(String) LANG-693 failed", Double.valueOf(Double.MAX_VALUE), NumberUtils
227239 .createNumber("" + Double.MAX_VALUE));
240
241 // LANG-822
242 // ensure that the underlying negative number would create a BigDecimal
243 final Number bigNum = NumberUtils.createNumber("-1.1E-700F");
244 assertNotNull(bigNum);
245 assertEquals(BigDecimal.class, bigNum.getClass());
246 }
247
248 @Test
249 public void TestLang747() {
250 assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000"));
251 assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000"));
252 assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000"));
253 assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000"));
254 assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF"));
255 assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000"));
256 assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF"));
257
258 // Leading zero tests
259 assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000"));
260 assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF"));
261 assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000"));
262 assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF"));
263
264 assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000"));
265 assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000"));
266 assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000"));
267 assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000"));
268 assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000"));
269 assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000"));
270 assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000"));
271 assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF"));
272 // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long
273 assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000"));
274 assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF"));
275
276 // Leading zero tests
277 assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000"));
278 assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000"));
279 assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF"));
280 // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long
281 assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000"));
282 assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF"));
283 }
284
285 @Test(expected=NumberFormatException.class)
286 // Check that the code fails to create a valid number when preceded by -- rather than -
287 public void testCreateNumberFailure_1() {
288 NumberUtils.createNumber("--1.1E-700F");
289 }
290
291 @Test(expected=NumberFormatException.class)
292 // Check that the code fails to create a valid number when both e and E are present (with decimal)
293 public void testCreateNumberFailure_2() {
294 NumberUtils.createNumber("-1.1E+0-7e00");
295 }
296
297 @Test(expected=NumberFormatException.class)
298 // Check that the code fails to create a valid number when both e and E are present (no decimal)
299 public void testCreateNumberFailure_3() {
300 NumberUtils.createNumber("-11E+0-7e00");
301 }
302
303 @Test(expected=NumberFormatException.class)
304 // Check that the code fails to create a valid number when both e and E are present (no decimal)
305 public void testCreateNumberFailure_4() {
306 NumberUtils.createNumber("1eE+00001");
307 }
308
309 // Tests to show when magnitude causes switch to next Number type
310 // Will probably need to be adjusted if code is changed to check precision (LANG-693)
311 @Test
312 public void testCreateNumberMagnitude() {
313 // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type
314 assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38"));
315 assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38"));
316
317 // Test Double.MAX_VALUE
318 assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308"));
319 // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal)
320 assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308"));
321
322 assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678"));
323 assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789"));
324
325 assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff"));
326 // Does not appear to be a way to create a literal BigInteger of this magnitude
327 assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("0x7fffffffffffffff0"));
328
329 assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff"));
330 assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("#7fffffffffffffff0"));
331
332 assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits
333 assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits
334
335 assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); // 63 bits
336 assertEquals(new BigInteger("1777777777777777777777",8), NumberUtils.createNumber("01777777777777777777777"));// 64 bits
228337 }
229338
230339 @Test
238347 this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
239348 }
240349
241 protected void testCreateFloatFailure(String str) {
350 protected void testCreateFloatFailure(final String str) {
242351 try {
243 Float value = NumberUtils.createFloat(str);
244 fail("createFloat(blank) failed: " + value);
245 } catch (NumberFormatException ex) {
352 final Float value = NumberUtils.createFloat(str);
353 fail("createFloat(\"" + str + "\") should have failed: " + value);
354 } catch (final NumberFormatException ex) {
246355 // empty
247356 }
248357 }
258367 this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
259368 }
260369
261 protected void testCreateDoubleFailure(String str) {
370 protected void testCreateDoubleFailure(final String str) {
262371 try {
263 Double value = NumberUtils.createDouble(str);
264 fail("createDouble(blank) failed: " + value);
265 } catch (NumberFormatException ex) {
372 final Double value = NumberUtils.createDouble(str);
373 fail("createDouble(\"" + str + "\") should have failed: " + value);
374 } catch (final NumberFormatException ex) {
266375 // empty
267376 }
268377 }
278387 this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
279388 }
280389
281 protected void testCreateIntegerFailure(String str) {
390 protected void testCreateIntegerFailure(final String str) {
282391 try {
283 Integer value = NumberUtils.createInteger(str);
284 fail("createInteger(blank) failed: " + value);
285 } catch (NumberFormatException ex) {
392 final Integer value = NumberUtils.createInteger(str);
393 fail("createInteger(\"" + str + "\") should have failed: " + value);
394 } catch (final NumberFormatException ex) {
286395 // empty
287396 }
288397 }
298407 this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
299408 }
300409
301 protected void testCreateLongFailure(String str) {
410 protected void testCreateLongFailure(final String str) {
302411 try {
303 Long value = NumberUtils.createLong(str);
304 fail("createLong(blank) failed: " + value);
305 } catch (NumberFormatException ex) {
412 final Long value = NumberUtils.createLong(str);
413 fail("createLong(\"" + str + "\") should have failed: " + value);
414 } catch (final NumberFormatException ex) {
306415 // empty
307416 }
308417 }
316425 this.testCreateBigIntegerFailure("\b\t\n\f\r");
317426 // Funky whitespaces
318427 this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
319 }
320
321 protected void testCreateBigIntegerFailure(String str) {
428 assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0xff"));
429 assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("#ff"));
430 assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0xff"));
431 assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0377"));
432 assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377"));
433 assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377"));
434 assertEquals("createBigInteger(String) failed", new BigInteger("-0"), NumberUtils.createBigInteger("-0"));
435 assertEquals("createBigInteger(String) failed", new BigInteger("0"), NumberUtils.createBigInteger("0"));
436 testCreateBigIntegerFailure("#");
437 testCreateBigIntegerFailure("-#");
438 testCreateBigIntegerFailure("0x");
439 testCreateBigIntegerFailure("-0x");
440 }
441
442 protected void testCreateBigIntegerFailure(final String str) {
322443 try {
323 BigInteger value = NumberUtils.createBigInteger(str);
324 fail("createBigInteger(blank) failed: " + value);
325 } catch (NumberFormatException ex) {
444 final BigInteger value = NumberUtils.createBigInteger(str);
445 fail("createBigInteger(\"" + str + "\") should have failed: " + value);
446 } catch (final NumberFormatException ex) {
326447 // empty
327448 }
328449 }
336457 this.testCreateBigDecimalFailure("\b\t\n\f\r");
337458 // Funky whitespaces
338459 this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
339 }
340
341 protected void testCreateBigDecimalFailure(String str) {
460 this.testCreateBigDecimalFailure("-"); // sign alone not valid
461 this.testCreateBigDecimalFailure("--"); // comment in NumberUtils suggests some implementations may incorrectly allow this
462 this.testCreateBigDecimalFailure("--0");
463 this.testCreateBigDecimalFailure("+"); // sign alone not valid
464 this.testCreateBigDecimalFailure("++"); // in case this was also allowed by some JVMs
465 this.testCreateBigDecimalFailure("++0");
466 }
467
468 protected void testCreateBigDecimalFailure(final String str) {
342469 try {
343 BigDecimal value = NumberUtils.createBigDecimal(str);
344 fail("createBigDecimal(blank) failed: " + value);
345 } catch (NumberFormatException ex) {
470 final BigDecimal value = NumberUtils.createBigDecimal(str);
471 fail("createBigDecimal(\"" + str + "\") should have failed: " + value);
472 } catch (final NumberFormatException ex) {
346473 // empty
347474 }
348475 }
655782 try {
656783 NumberUtils.max(d);
657784 fail("No exception was thrown for null input.");
658 } catch (IllegalArgumentException ex) {}
785 } catch (final IllegalArgumentException ex) {}
659786
660787 try {
661788 NumberUtils.max(new double[0]);
662789 fail("No exception was thrown for empty input.");
663 } catch (IllegalArgumentException ex) {}
790 } catch (final IllegalArgumentException ex) {}
664791
665792 assertEquals(
666793 "max(double[]) failed for array length 1",
736863
737864 @Test
738865 public void testMinimumShort() {
739 short low = 1234;
740 short mid = 1234 + 1;
741 short high = 1234 + 2;
866 final short low = 1234;
867 final short mid = 1234 + 1;
868 final short high = 1234 + 2;
742869 assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high));
743870 assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high));
744871 assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low));
747874
748875 @Test
749876 public void testMinimumByte() {
750 byte low = 123;
751 byte mid = 123 + 1;
752 byte high = 123 + 2;
877 final byte low = 123;
878 final byte mid = 123 + 1;
879 final byte high = 123 + 2;
753880 assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high));
754881 assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high));
755882 assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low));
758885
759886 @Test
760887 public void testMinimumDouble() {
761 double low = 12.3;
762 double mid = 12.3 + 1;
763 double high = 12.3 + 2;
888 final double low = 12.3;
889 final double mid = 12.3 + 1;
890 final double high = 12.3 + 2;
764891 assertEquals(low, NumberUtils.min(low, mid, high), 0.0001);
765892 assertEquals(low, NumberUtils.min(mid, low, high), 0.0001);
766893 assertEquals(low, NumberUtils.min(mid, high, low), 0.0001);
770897
771898 @Test
772899 public void testMinimumFloat() {
773 float low = 12.3f;
774 float mid = 12.3f + 1;
775 float high = 12.3f + 2;
900 final float low = 12.3f;
901 final float mid = 12.3f + 1;
902 final float high = 12.3f + 2;
776903 assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f);
777904 assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f);
778905 assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f);
800927
801928 @Test
802929 public void testMaximumShort() {
803 short low = 1234;
804 short mid = 1234 + 1;
805 short high = 1234 + 2;
930 final short low = 1234;
931 final short mid = 1234 + 1;
932 final short high = 1234 + 2;
806933 assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high));
807934 assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high));
808935 assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low));
811938
812939 @Test
813940 public void testMaximumByte() {
814 byte low = 123;
815 byte mid = 123 + 1;
816 byte high = 123 + 2;
941 final byte low = 123;
942 final byte mid = 123 + 1;
943 final byte high = 123 + 2;
817944 assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high));
818945 assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high));
819946 assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low));
822949
823950 @Test
824951 public void testMaximumDouble() {
825 double low = 12.3;
826 double mid = 12.3 + 1;
827 double high = 12.3 + 2;
952 final double low = 12.3;
953 final double mid = 12.3 + 1;
954 final double high = 12.3 + 2;
828955 assertEquals(high, NumberUtils.max(low, mid, high), 0.0001);
829956 assertEquals(high, NumberUtils.max(mid, low, high), 0.0001);
830957 assertEquals(high, NumberUtils.max(mid, high, low), 0.0001);
834961
835962 @Test
836963 public void testMaximumFloat() {
837 float low = 12.3f;
838 float mid = 12.3f + 1;
839 float high = 12.3f + 2;
964 final float low = 12.3f;
965 final float mid = 12.3f + 1;
966 final float high = 12.3f + 2;
840967 assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f);
841968 assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f);
842969 assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f);
11891316 assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val));
11901317 }
11911318
1192 private boolean checkCreateNumber(String val) {
1319 private boolean checkCreateNumber(final String val) {
11931320 try {
1194 Object obj = NumberUtils.createNumber(val);
1321 final Object obj = NumberUtils.createNumber(val);
11951322 if (obj == null) {
11961323 return false;
11971324 }
11981325 return true;
1199 } catch (NumberFormatException e) {
1326 } catch (final NumberFormatException e) {
12001327 return false;
12011328 }
12021329 }
12571384 assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN)));
12581385 assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN)));
12591386
1260 double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
1387 final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
12611388 assertTrue(Double.isNaN(NumberUtils.max(a)));
12621389 assertTrue(Double.isNaN(NumberUtils.min(a)));
12631390
1264 double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
1391 final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
12651392 assertTrue(Double.isNaN(NumberUtils.max(b)));
12661393 assertTrue(Double.isNaN(NumberUtils.min(b)));
12671394
1268 float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
1395 final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
12691396 assertTrue(Float.isNaN(NumberUtils.max(aF)));
12701397
1271 float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
1398 final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
12721399 assertTrue(Float.isNaN(NumberUtils.max(bF)));
12731400 }
12741401
1616
1717 package org.apache.commons.lang3.mutable;
1818
19 import junit.framework.TestCase;
19 import org.junit.Test;
20 import static org.junit.Assert.*;
2021
2122 /**
2223 * JUnit tests.
2324 *
2425 * @since 2.2
2526 * @see MutableBoolean
26 * @version $Id: MutableBooleanTest.java 1088899 2011-04-05 05:31:27Z bayard $
27 * @version $Id: MutableBooleanTest.java 1388108 2012-09-20 16:36:57Z sebb $
2728 */
28 public class MutableBooleanTest extends TestCase {
29 public class MutableBooleanTest {
2930
30 public MutableBooleanTest(String testName) {
31 super(testName);
32 }
33
31 @Test
3432 public void testCompareTo() {
3533 final MutableBoolean mutBool = new MutableBoolean(false);
3634
3937 mutBool.setValue(true);
4038 assertEquals(+1, mutBool.compareTo(new MutableBoolean(false)));
4139 assertEquals(0, mutBool.compareTo(new MutableBoolean(true)));
42
43 try {
44 mutBool.compareTo(null);
45 fail();
46 } catch (NullPointerException ex) {
47 }
40 }
41
42 @Test(expected=NullPointerException.class)
43 public void testCompareToNull() {
44 final MutableBoolean mutBool = new MutableBoolean(false);
45 mutBool.compareTo(null);
4846 }
4947
5048 // ----------------------------------------------------------------
49 @Test
5150 public void testConstructors() {
52 assertEquals(false, new MutableBoolean().booleanValue());
51 assertFalse(new MutableBoolean().booleanValue());
5352
54 assertEquals(true, new MutableBoolean(true).booleanValue());
55 assertEquals(false, new MutableBoolean(false).booleanValue());
53 assertTrue(new MutableBoolean(true).booleanValue());
54 assertFalse(new MutableBoolean(false).booleanValue());
5655
57 assertEquals(true, new MutableBoolean(Boolean.TRUE).booleanValue());
58 assertEquals(false, new MutableBoolean(Boolean.FALSE).booleanValue());
56 assertTrue(new MutableBoolean(Boolean.TRUE).booleanValue());
57 assertFalse(new MutableBoolean(Boolean.FALSE).booleanValue());
5958
60 try {
61 new MutableBoolean(null);
62 fail();
63 } catch (NullPointerException ex) {
64 }
6559 }
6660
61 @Test(expected=NullPointerException.class)
62 public void testConstructorNull() {
63 new MutableBoolean(null);
64 }
65
66 @Test
6767 public void testEquals() {
6868 final MutableBoolean mutBoolA = new MutableBoolean(false);
6969 final MutableBoolean mutBoolB = new MutableBoolean(false);
7070 final MutableBoolean mutBoolC = new MutableBoolean(true);
7171
72 assertEquals(true, mutBoolA.equals(mutBoolA));
73 assertEquals(true, mutBoolA.equals(mutBoolB));
74 assertEquals(true, mutBoolB.equals(mutBoolA));
75 assertEquals(true, mutBoolB.equals(mutBoolB));
76 assertEquals(false, mutBoolA.equals(mutBoolC));
77 assertEquals(false, mutBoolB.equals(mutBoolC));
78 assertEquals(true, mutBoolC.equals(mutBoolC));
79 assertEquals(false, mutBoolA.equals(null));
80 assertEquals(false, mutBoolA.equals(Boolean.FALSE));
81 assertEquals(false, mutBoolA.equals("false"));
72 assertTrue(mutBoolA.equals(mutBoolA));
73 assertTrue(mutBoolA.equals(mutBoolB));
74 assertTrue(mutBoolB.equals(mutBoolA));
75 assertTrue(mutBoolB.equals(mutBoolB));
76 assertFalse(mutBoolA.equals(mutBoolC));
77 assertFalse(mutBoolB.equals(mutBoolC));
78 assertTrue(mutBoolC.equals(mutBoolC));
79 assertFalse(mutBoolA.equals(null));
80 assertFalse(mutBoolA.equals(Boolean.FALSE));
81 assertFalse(mutBoolA.equals("false"));
8282 }
8383
84 @Test
8485 public void testGetSet() {
85 assertEquals(false, new MutableBoolean().booleanValue());
86 assertFalse(new MutableBoolean().booleanValue());
8687 assertEquals(Boolean.FALSE, new MutableBoolean().getValue());
8788
8889 final MutableBoolean mutBool = new MutableBoolean(false);
8990 assertEquals(Boolean.FALSE, mutBool.toBoolean());
90 assertEquals(false, mutBool.booleanValue());
91 assertEquals(true, mutBool.isFalse());
92 assertEquals(false, mutBool.isTrue());
91 assertFalse(mutBool.booleanValue());
92 assertTrue(mutBool.isFalse());
93 assertFalse(mutBool.isTrue());
9394
9495 mutBool.setValue(Boolean.TRUE);
9596 assertEquals(Boolean.TRUE, mutBool.toBoolean());
96 assertEquals(true, mutBool.booleanValue());
97 assertEquals(false, mutBool.isFalse());
98 assertEquals(true, mutBool.isTrue());
97 assertTrue(mutBool.booleanValue());
98 assertFalse(mutBool.isFalse());
99 assertTrue(mutBool.isTrue());
99100
100101 mutBool.setValue(false);
101 assertEquals(false, mutBool.booleanValue());
102 assertFalse(mutBool.booleanValue());
102103
103104 mutBool.setValue(true);
104 assertEquals(true, mutBool.booleanValue());
105 assertTrue(mutBool.booleanValue());
105106
106 try {
107 mutBool.setValue(null);
108 fail();
109 } catch (NullPointerException ex) {
110 }
111107 }
112108
109 @Test(expected=NullPointerException.class)
110 public void testSetNull() {
111 final MutableBoolean mutBool = new MutableBoolean(false);
112 mutBool.setValue(null);
113 }
114
115 @Test
113116 public void testHashCode() {
114117 final MutableBoolean mutBoolA = new MutableBoolean(false);
115118 final MutableBoolean mutBoolB = new MutableBoolean(false);
116119 final MutableBoolean mutBoolC = new MutableBoolean(true);
117120
118 assertEquals(true, mutBoolA.hashCode() == mutBoolA.hashCode());
119 assertEquals(true, mutBoolA.hashCode() == mutBoolB.hashCode());
120 assertEquals(false, mutBoolA.hashCode() == mutBoolC.hashCode());
121 assertEquals(true, mutBoolA.hashCode() == Boolean.FALSE.hashCode());
122 assertEquals(true, mutBoolC.hashCode() == Boolean.TRUE.hashCode());
121 assertEquals(mutBoolA.hashCode(), mutBoolA.hashCode());
122 assertEquals(mutBoolA.hashCode(), mutBoolB.hashCode());
123 assertFalse(mutBoolA.hashCode() == mutBoolC.hashCode());
124 assertEquals(mutBoolA.hashCode(), Boolean.FALSE.hashCode());
125 assertEquals(mutBoolC.hashCode(), Boolean.TRUE.hashCode());
123126 }
124127
128 @Test
125129 public void testToString() {
126130 assertEquals(Boolean.FALSE.toString(), new MutableBoolean(false).toString());
127131 assertEquals(Boolean.TRUE.toString(), new MutableBoolean(true).toString());
1515 */
1616 package org.apache.commons.lang3.mutable;
1717
18 import junit.framework.TestCase;
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1920
2021 /**
2122 * JUnit tests.
2223 *
23 * @version $Id: MutableByteTest.java 1153484 2011-08-03 13:39:42Z ggregory $
24 * @version $Id: MutableByteTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2425 * @see MutableByte
2526 */
26 public class MutableByteTest extends TestCase {
27
28 public MutableByteTest(String testName) {
29 super(testName);
30 }
27 public class MutableByteTest {
3128
3229 // ----------------------------------------------------------------
30 @Test
3331 public void testConstructors() {
3432 assertEquals((byte) 0, new MutableByte().byteValue());
3533
4038
4139 assertEquals((byte) 2, new MutableByte("2").byteValue());
4240
43 try {
44 new MutableByte((Number)null);
45 fail();
46 } catch (NullPointerException ex) {}
4741 }
4842
43 @Test(expected=NullPointerException.class)
44 public void testConstructorNull() {
45 new MutableByte((Number)null);
46 }
47
48 @Test
4949 public void testGetSet() {
5050 final MutableByte mutNum = new MutableByte((byte) 0);
5151 assertEquals((byte) 0, new MutableByte().byteValue());
6262 mutNum.setValue(new MutableByte((byte) 3));
6363 assertEquals((byte) 3, mutNum.byteValue());
6464 assertEquals(Byte.valueOf((byte) 3), mutNum.getValue());
65 try {
66 mutNum.setValue(null);
67 fail();
68 } catch (NullPointerException ex) {}
6965 }
7066
67 @Test(expected=NullPointerException.class)
68 public void testSetNull() {
69 final MutableByte mutNum = new MutableByte((byte) 0);
70 mutNum.setValue(null);
71 }
72
73 @Test
7174 public void testEquals() {
7275 final MutableByte mutNumA = new MutableByte((byte) 0);
7376 final MutableByte mutNumB = new MutableByte((byte) 0);
7477 final MutableByte mutNumC = new MutableByte((byte) 1);
7578
76 assertEquals(true, mutNumA.equals(mutNumA));
77 assertEquals(true, mutNumA.equals(mutNumB));
78 assertEquals(true, mutNumB.equals(mutNumA));
79 assertEquals(true, mutNumB.equals(mutNumB));
80 assertEquals(false, mutNumA.equals(mutNumC));
81 assertEquals(false, mutNumB.equals(mutNumC));
82 assertEquals(true, mutNumC.equals(mutNumC));
83 assertEquals(false, mutNumA.equals(null));
84 assertEquals(false, mutNumA.equals(Byte.valueOf((byte) 0)));
85 assertEquals(false, mutNumA.equals("0"));
79 assertTrue(mutNumA.equals(mutNumA));
80 assertTrue(mutNumA.equals(mutNumB));
81 assertTrue(mutNumB.equals(mutNumA));
82 assertTrue(mutNumB.equals(mutNumB));
83 assertFalse(mutNumA.equals(mutNumC));
84 assertFalse(mutNumB.equals(mutNumC));
85 assertTrue(mutNumC.equals(mutNumC));
86 assertFalse(mutNumA.equals(null));
87 assertFalse(mutNumA.equals(Byte.valueOf((byte) 0)));
88 assertFalse(mutNumA.equals("0"));
8689 }
8790
91 @Test
8892 public void testHashCode() {
8993 final MutableByte mutNumA = new MutableByte((byte) 0);
9094 final MutableByte mutNumB = new MutableByte((byte) 0);
9195 final MutableByte mutNumC = new MutableByte((byte) 1);
9296
93 assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode());
94 assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode());
95 assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode());
96 assertEquals(true, mutNumA.hashCode() == Byte.valueOf((byte) 0).hashCode());
97 assertTrue(mutNumA.hashCode() == mutNumA.hashCode());
98 assertTrue(mutNumA.hashCode() == mutNumB.hashCode());
99 assertFalse(mutNumA.hashCode() == mutNumC.hashCode());
100 assertTrue(mutNumA.hashCode() == Byte.valueOf((byte) 0).hashCode());
97101 }
98102
103 @Test
99104 public void testCompareTo() {
100105 final MutableByte mutNum = new MutableByte((byte) 0);
101106
102107 assertEquals((byte) 0, mutNum.compareTo(new MutableByte((byte) 0)));
103108 assertEquals((byte) +1, mutNum.compareTo(new MutableByte((byte) -1)));
104109 assertEquals((byte) -1, mutNum.compareTo(new MutableByte((byte) 1)));
105 try {
106 mutNum.compareTo(null);
107 fail();
108 } catch (NullPointerException ex) {}
109110 }
110111
112 @Test(expected=NullPointerException.class)
113 public void testCompareToNull() {
114 final MutableByte mutNum = new MutableByte((byte) 0);
115 mutNum.compareTo(null);
116 }
117
118 @Test
111119 public void testPrimitiveValues() {
112 MutableByte mutNum = new MutableByte( (byte) 1 );
120 final MutableByte mutNum = new MutableByte( (byte) 1 );
113121
114122 assertEquals( 1.0F, mutNum.floatValue(), 0 );
115123 assertEquals( 1.0, mutNum.doubleValue(), 0 );
119127 assertEquals( 1L, mutNum.longValue() );
120128 }
121129
130 @Test
122131 public void testToByte() {
123132 assertEquals(Byte.valueOf((byte) 0), new MutableByte((byte) 0).toByte());
124133 assertEquals(Byte.valueOf((byte) 123), new MutableByte((byte) 123).toByte());
125134 }
126135
136 @Test
127137 public void testIncrement() {
128 MutableByte mutNum = new MutableByte((byte) 1);
138 final MutableByte mutNum = new MutableByte((byte) 1);
129139 mutNum.increment();
130140
131141 assertEquals(2, mutNum.intValue());
132142 assertEquals(2L, mutNum.longValue());
133143 }
134144
145 @Test
135146 public void testDecrement() {
136 MutableByte mutNum = new MutableByte((byte) 1);
147 final MutableByte mutNum = new MutableByte((byte) 1);
137148 mutNum.decrement();
138149
139150 assertEquals(0, mutNum.intValue());
140151 assertEquals(0L, mutNum.longValue());
141152 }
142153
154 @Test
143155 public void testAddValuePrimitive() {
144 MutableByte mutNum = new MutableByte((byte) 1);
156 final MutableByte mutNum = new MutableByte((byte) 1);
145157 mutNum.add((byte)1);
146158
147159 assertEquals((byte) 2, mutNum.byteValue());
148160 }
149161
162 @Test
150163 public void testAddValueObject() {
151 MutableByte mutNum = new MutableByte((byte) 1);
164 final MutableByte mutNum = new MutableByte((byte) 1);
152165 mutNum.add(Integer.valueOf(1));
153166
154167 assertEquals((byte) 2, mutNum.byteValue());
155168 }
156169
170 @Test
157171 public void testSubtractValuePrimitive() {
158 MutableByte mutNum = new MutableByte((byte) 1);
172 final MutableByte mutNum = new MutableByte((byte) 1);
159173 mutNum.subtract((byte) 1);
160174
161175 assertEquals((byte) 0, mutNum.byteValue());
162176 }
163177
178 @Test
164179 public void testSubtractValueObject() {
165 MutableByte mutNum = new MutableByte((byte) 1);
180 final MutableByte mutNum = new MutableByte((byte) 1);
166181 mutNum.subtract(Integer.valueOf(1));
167182
168183 assertEquals((byte) 0, mutNum.byteValue());
169184 }
170185
186 @Test
171187 public void testToString() {
172188 assertEquals("0", new MutableByte((byte) 0).toString());
173189 assertEquals("10", new MutableByte((byte) 10).toString());
1515 */
1616 package org.apache.commons.lang3.mutable;
1717
18 import junit.framework.TestCase;
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1920
2021 /**
2122 * JUnit tests.
2223 *
23 * @version $Id: MutableDoubleTest.java 1153490 2011-08-03 13:53:35Z ggregory $
24 * @version $Id: MutableDoubleTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2425 * @see MutableDouble
2526 */
26 public class MutableDoubleTest extends TestCase {
27
28 public MutableDoubleTest(String testName) {
29 super(testName);
30 }
27 public class MutableDoubleTest {
3128
3229 // ----------------------------------------------------------------
30 @Test
3331 public void testConstructors() {
3432 assertEquals(0d, new MutableDouble().doubleValue(), 0.0001d);
3533
4038
4139 assertEquals(2d, new MutableDouble("2.0").doubleValue(), 0.0001d);
4240
43 try {
44 new MutableDouble((Number)null);
45 fail();
46 } catch (NullPointerException ex) {}
47 }
48
41 }
42
43 @Test(expected=NullPointerException.class)
44 public void testConstructorNull() {
45 new MutableDouble((Number)null);
46 }
47
48 @Test
4949 public void testGetSet() {
5050 final MutableDouble mutNum = new MutableDouble(0d);
5151 assertEquals(0d, new MutableDouble().doubleValue(), 0.0001d);
6262 mutNum.setValue(new MutableDouble(3d));
6363 assertEquals(3d, mutNum.doubleValue(), 0.0001d);
6464 assertEquals(Double.valueOf(3d), mutNum.getValue());
65 try {
66 mutNum.setValue(null);
67 fail();
68 } catch (NullPointerException ex) {}
69 }
70
65 }
66
67 @Test(expected=NullPointerException.class)
68 public void testSetNull() {
69 final MutableDouble mutNum = new MutableDouble(0d);
70 mutNum.setValue(null);
71 }
72
73 @Test
7174 public void testNanInfinite() {
7275 MutableDouble mutNum = new MutableDouble(Double.NaN);
73 assertEquals(true, mutNum.isNaN());
76 assertTrue(mutNum.isNaN());
7477
7578 mutNum = new MutableDouble(Double.POSITIVE_INFINITY);
76 assertEquals(true, mutNum.isInfinite());
79 assertTrue(mutNum.isInfinite());
7780
7881 mutNum = new MutableDouble(Double.NEGATIVE_INFINITY);
79 assertEquals(true, mutNum.isInfinite());
80 }
81
82 assertTrue(mutNum.isInfinite());
83 }
84
85 @Test
8286 public void testEquals() {
8387 final MutableDouble mutNumA = new MutableDouble(0d);
8488 final MutableDouble mutNumB = new MutableDouble(0d);
8589 final MutableDouble mutNumC = new MutableDouble(1d);
8690
87 assertEquals(true, mutNumA.equals(mutNumA));
88 assertEquals(true, mutNumA.equals(mutNumB));
89 assertEquals(true, mutNumB.equals(mutNumA));
90 assertEquals(true, mutNumB.equals(mutNumB));
91 assertEquals(false, mutNumA.equals(mutNumC));
92 assertEquals(false, mutNumB.equals(mutNumC));
93 assertEquals(true, mutNumC.equals(mutNumC));
94 assertEquals(false, mutNumA.equals(null));
95 assertEquals(false, mutNumA.equals(Double.valueOf(0d)));
96 assertEquals(false, mutNumA.equals("0"));
97 }
98
91 assertTrue(mutNumA.equals(mutNumA));
92 assertTrue(mutNumA.equals(mutNumB));
93 assertTrue(mutNumB.equals(mutNumA));
94 assertTrue(mutNumB.equals(mutNumB));
95 assertFalse(mutNumA.equals(mutNumC));
96 assertFalse(mutNumB.equals(mutNumC));
97 assertTrue(mutNumC.equals(mutNumC));
98 assertFalse(mutNumA.equals(null));
99 assertFalse(mutNumA.equals(Double.valueOf(0d)));
100 assertFalse(mutNumA.equals("0"));
101 }
102
103 @Test
99104 public void testHashCode() {
100105 final MutableDouble mutNumA = new MutableDouble(0d);
101106 final MutableDouble mutNumB = new MutableDouble(0d);
102107 final MutableDouble mutNumC = new MutableDouble(1d);
103108
104 assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode());
105 assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode());
106 assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode());
107 assertEquals(true, mutNumA.hashCode() == Double.valueOf(0d).hashCode());
108 }
109
109 assertTrue(mutNumA.hashCode() == mutNumA.hashCode());
110 assertTrue(mutNumA.hashCode() == mutNumB.hashCode());
111 assertFalse(mutNumA.hashCode() == mutNumC.hashCode());
112 assertTrue(mutNumA.hashCode() == Double.valueOf(0d).hashCode());
113 }
114
115 @Test
110116 public void testCompareTo() {
111117 final MutableDouble mutNum = new MutableDouble(0d);
112118
113119 assertEquals(0, mutNum.compareTo(new MutableDouble(0d)));
114120 assertEquals(+1, mutNum.compareTo(new MutableDouble(-1d)));
115121 assertEquals(-1, mutNum.compareTo(new MutableDouble(1d)));
116 try {
117 mutNum.compareTo(null);
118 fail();
119 } catch (NullPointerException ex) {}
120 }
121
122 }
123
124 @Test(expected=NullPointerException.class)
125 public void testCompareToNull() {
126 final MutableDouble mutNum = new MutableDouble(0d);
127 mutNum.compareTo(null);
128 }
129
130 @Test
122131 public void testPrimitiveValues() {
123 MutableDouble mutNum = new MutableDouble(1.7);
132 final MutableDouble mutNum = new MutableDouble(1.7);
124133
125134 assertEquals( 1.7F, mutNum.floatValue(), 0 );
126135 assertEquals( 1.7, mutNum.doubleValue(), 0 );
130139 assertEquals( 1L, mutNum.longValue() );
131140 }
132141
142 @Test
133143 public void testToDouble() {
134144 assertEquals(Double.valueOf(0d), new MutableDouble(0d).toDouble());
135145 assertEquals(Double.valueOf(12.3d), new MutableDouble(12.3d).toDouble());
136146 }
137147
148 @Test
138149 public void testIncrement() {
139 MutableDouble mutNum = new MutableDouble(1);
150 final MutableDouble mutNum = new MutableDouble(1);
140151 mutNum.increment();
141152
142153 assertEquals(2, mutNum.intValue());
143154 assertEquals(2L, mutNum.longValue());
144155 }
145156
157 @Test
146158 public void testDecrement() {
147 MutableDouble mutNum = new MutableDouble(1);
159 final MutableDouble mutNum = new MutableDouble(1);
148160 mutNum.decrement();
149161
150162 assertEquals(0, mutNum.intValue());
151163 assertEquals(0L, mutNum.longValue());
152164 }
153165
166 @Test
154167 public void testAddValuePrimitive() {
155 MutableDouble mutNum = new MutableDouble(1);
168 final MutableDouble mutNum = new MutableDouble(1);
156169 mutNum.add(1.1d);
157170
158171 assertEquals(2.1d, mutNum.doubleValue(), 0.01d);
159172 }
160173
174 @Test
161175 public void testAddValueObject() {
162 MutableDouble mutNum = new MutableDouble(1);
176 final MutableDouble mutNum = new MutableDouble(1);
163177 mutNum.add(Double.valueOf(1.1d));
164178
165179 assertEquals(2.1d, mutNum.doubleValue(), 0.01d);
166180 }
167181
182 @Test
168183 public void testSubtractValuePrimitive() {
169 MutableDouble mutNum = new MutableDouble(1);
184 final MutableDouble mutNum = new MutableDouble(1);
170185 mutNum.subtract(0.9d);
171186
172187 assertEquals(0.1d, mutNum.doubleValue(), 0.01d);
173188 }
174189
190 @Test
175191 public void testSubtractValueObject() {
176 MutableDouble mutNum = new MutableDouble(1);
192 final MutableDouble mutNum = new MutableDouble(1);
177193 mutNum.subtract(Double.valueOf(0.9d));
178194
179195 assertEquals(0.1d, mutNum.doubleValue(), 0.01d);
180196 }
181197
198 @Test
182199 public void testToString() {
183200 assertEquals("0.0", new MutableDouble(0d).toString());
184201 assertEquals("10.0", new MutableDouble(10d).toString());
1515 */
1616 package org.apache.commons.lang3.mutable;
1717
18 import junit.framework.TestCase;
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1920
2021 /**
2122 * JUnit tests.
2223 *
23 * @version $Id: MutableFloatTest.java 1153490 2011-08-03 13:53:35Z ggregory $
24 * @version $Id: MutableFloatTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2425 * @see MutableFloat
2526 */
26 public class MutableFloatTest extends TestCase {
27
28 public MutableFloatTest(String testName) {
29 super(testName);
30 }
27 public class MutableFloatTest {
3128
3229 // ----------------------------------------------------------------
30 @Test
3331 public void testConstructors() {
3432 assertEquals(0f, new MutableFloat().floatValue(), 0.0001f);
3533
4038
4139 assertEquals(2f, new MutableFloat("2.0").floatValue(), 0.0001f);
4240
43 try {
44 new MutableFloat((Number)null);
45 fail();
46 } catch (NullPointerException ex) {}
47 }
48
41 }
42
43 @Test(expected=NullPointerException.class)
44 public void testConstructorNull() {
45 new MutableFloat((Number)null);
46 }
47
48 @Test
4949 public void testGetSet() {
5050 final MutableFloat mutNum = new MutableFloat(0f);
5151 assertEquals(0f, new MutableFloat().floatValue(), 0.0001f);
6262 mutNum.setValue(new MutableFloat(3f));
6363 assertEquals(3f, mutNum.floatValue(), 0.0001f);
6464 assertEquals(Float.valueOf(3f), mutNum.getValue());
65 try {
66 mutNum.setValue(null);
67 fail();
68 } catch (NullPointerException ex) {}
69 }
70
65 }
66
67 @Test(expected=NullPointerException.class)
68 public void testSetNull() {
69 final MutableFloat mutNum = new MutableFloat(0f);
70 mutNum.setValue(null);
71 }
72
73 @Test
7174 public void testNanInfinite() {
7275 MutableFloat mutNum = new MutableFloat(Float.NaN);
73 assertEquals(true, mutNum.isNaN());
76 assertTrue(mutNum.isNaN());
7477
7578 mutNum = new MutableFloat(Float.POSITIVE_INFINITY);
76 assertEquals(true, mutNum.isInfinite());
79 assertTrue(mutNum.isInfinite());
7780
7881 mutNum = new MutableFloat(Float.NEGATIVE_INFINITY);
79 assertEquals(true, mutNum.isInfinite());
80 }
81
82 assertTrue(mutNum.isInfinite());
83 }
84
85 @Test
8286 public void testEquals() {
8387 final MutableFloat mutNumA = new MutableFloat(0f);
8488 final MutableFloat mutNumB = new MutableFloat(0f);
8589 final MutableFloat mutNumC = new MutableFloat(1f);
8690
87 assertEquals(true, mutNumA.equals(mutNumA));
88 assertEquals(true, mutNumA.equals(mutNumB));
89 assertEquals(true, mutNumB.equals(mutNumA));
90 assertEquals(true, mutNumB.equals(mutNumB));
91 assertEquals(false, mutNumA.equals(mutNumC));
92 assertEquals(false, mutNumB.equals(mutNumC));
93 assertEquals(true, mutNumC.equals(mutNumC));
94 assertEquals(false, mutNumA.equals(null));
95 assertEquals(false, mutNumA.equals(Float.valueOf(0f)));
96 assertEquals(false, mutNumA.equals("0"));
97 }
98
91 assertTrue(mutNumA.equals(mutNumA));
92 assertTrue(mutNumA.equals(mutNumB));
93 assertTrue(mutNumB.equals(mutNumA));
94 assertTrue(mutNumB.equals(mutNumB));
95 assertFalse(mutNumA.equals(mutNumC));
96 assertFalse(mutNumB.equals(mutNumC));
97 assertTrue(mutNumC.equals(mutNumC));
98 assertFalse(mutNumA.equals(null));
99 assertFalse(mutNumA.equals(Float.valueOf(0f)));
100 assertFalse(mutNumA.equals("0"));
101 }
102
103 @Test
99104 public void testHashCode() {
100105 final MutableFloat mutNumA = new MutableFloat(0f);
101106 final MutableFloat mutNumB = new MutableFloat(0f);
102107 final MutableFloat mutNumC = new MutableFloat(1f);
103108
104 assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode());
105 assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode());
106 assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode());
107 assertEquals(true, mutNumA.hashCode() == Float.valueOf(0f).hashCode());
108 }
109
109 assertTrue(mutNumA.hashCode() == mutNumA.hashCode());
110 assertTrue(mutNumA.hashCode() == mutNumB.hashCode());
111 assertFalse(mutNumA.hashCode() == mutNumC.hashCode());
112 assertTrue(mutNumA.hashCode() == Float.valueOf(0f).hashCode());
113 }
114
115 @Test
110116 public void testCompareTo() {
111117 final MutableFloat mutNum = new MutableFloat(0f);
112118
113119 assertEquals(0, mutNum.compareTo(new MutableFloat(0f)));
114120 assertEquals(+1, mutNum.compareTo(new MutableFloat(-1f)));
115121 assertEquals(-1, mutNum.compareTo(new MutableFloat(1f)));
116 try {
117 mutNum.compareTo(null);
118 fail();
119 } catch (NullPointerException ex) {}
120 }
121
122 }
123
124 @Test(expected=NullPointerException.class)
125 public void testCompareToNull() {
126 final MutableFloat mutNum = new MutableFloat(0f);
127 mutNum.compareTo(null);
128 }
129
130 @Test
122131 public void testPrimitiveValues() {
123 MutableFloat mutNum = new MutableFloat(1.7F);
132 final MutableFloat mutNum = new MutableFloat(1.7F);
124133
125134 assertEquals( 1, mutNum.intValue() );
126135 assertEquals( 1.7, mutNum.doubleValue(), 0.00001 );
130139 assertEquals( 1L, mutNum.longValue() );
131140 }
132141
142 @Test
133143 public void testToFloat() {
134144 assertEquals(Float.valueOf(0f), new MutableFloat(0f).toFloat());
135145 assertEquals(Float.valueOf(12.3f), new MutableFloat(12.3f).toFloat());
136146 }
137147
148 @Test
138149 public void testIncrement() {
139 MutableFloat mutNum = new MutableFloat(1);
150 final MutableFloat mutNum = new MutableFloat(1);
140151 mutNum.increment();
141152
142153 assertEquals(2, mutNum.intValue());
143154 assertEquals(2L, mutNum.longValue());
144155 }
145156
157 @Test
146158 public void testDecrement() {
147 MutableFloat mutNum = new MutableFloat(1);
159 final MutableFloat mutNum = new MutableFloat(1);
148160 mutNum.decrement();
149161
150162 assertEquals(0, mutNum.intValue());
151163 assertEquals(0L, mutNum.longValue());
152164 }
153165
166 @Test
154167 public void testAddValuePrimitive() {
155 MutableFloat mutNum = new MutableFloat(1);
168 final MutableFloat mutNum = new MutableFloat(1);
156169 mutNum.add(1.1f);
157170
158171 assertEquals(2.1f, mutNum.floatValue(), 0.01f);
159172 }
160173
174 @Test
161175 public void testAddValueObject() {
162 MutableFloat mutNum = new MutableFloat(1);
176 final MutableFloat mutNum = new MutableFloat(1);
163177 mutNum.add(Float.valueOf(1.1f));
164178
165179 assertEquals(2.1f, mutNum.floatValue(), 0.01f);
166180 }
167181
182 @Test
168183 public void testSubtractValuePrimitive() {
169 MutableFloat mutNum = new MutableFloat(1);
184 final MutableFloat mutNum = new MutableFloat(1);
170185 mutNum.subtract(0.9f);
171186
172187 assertEquals(0.1f, mutNum.floatValue(), 0.01f);
173188 }
174189
190 @Test
175191 public void testSubtractValueObject() {
176 MutableFloat mutNum = new MutableFloat(1);
192 final MutableFloat mutNum = new MutableFloat(1);
177193 mutNum.subtract(Float.valueOf(0.9f));
178194
179195 assertEquals(0.1f, mutNum.floatValue(), 0.01f);
180196 }
181197
198 @Test
182199 public void testToString() {
183200 assertEquals("0.0", new MutableFloat(0f).toString());
184201 assertEquals("10.0", new MutableFloat(10f).toString());
1515 */
1616 package org.apache.commons.lang3.mutable;
1717
18 import junit.framework.TestCase;
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1920
2021 /**
2122 * JUnit tests.
2223 *
23 * @version $Id: MutableIntTest.java 1153484 2011-08-03 13:39:42Z ggregory $
24 * @version $Id: MutableIntTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2425 * @see MutableInt
2526 */
26 public class MutableIntTest extends TestCase {
27
28 public MutableIntTest(String testName) {
29 super(testName);
30 }
27 public class MutableIntTest {
3128
3229 // ----------------------------------------------------------------
30 @Test
3331 public void testConstructors() {
3432 assertEquals(0, new MutableInt().intValue());
3533
4038
4139 assertEquals(2, new MutableInt("2").intValue());
4240
43 try {
44 new MutableInt((Number)null);
45 fail();
46 } catch (NullPointerException ex) {}
47 }
48
41 }
42
43 @Test(expected=NullPointerException.class)
44 public void testConstructorNull() {
45 new MutableInt((Number)null);
46 }
47
48 @Test
4949 public void testGetSet() {
5050 final MutableInt mutNum = new MutableInt(0);
5151 assertEquals(0, new MutableInt().intValue());
6262 mutNum.setValue(new MutableLong(3));
6363 assertEquals(3, mutNum.intValue());
6464 assertEquals(Integer.valueOf(3), mutNum.getValue());
65 try {
66 mutNum.setValue(null);
67 fail();
68 } catch (NullPointerException ex) {}
69 }
70
65 }
66
67 @Test(expected=NullPointerException.class)
68 public void testSetNull() {
69 final MutableInt mutNum = new MutableInt(0);
70 mutNum.setValue(null);
71 }
72
73 @Test
7174 public void testEquals() {
7275 this.testEquals(new MutableInt(0), new MutableInt(0), new MutableInt(1));
7376 // Should Numbers be supported? GaryG July-21-2005.
8083 * @param numC must not equal numA; must not equal numC.
8184 */
8285 void testEquals(final Number numA, final Number numB, final Number numC) {
83 assertEquals(true, numA.equals(numA));
84 assertEquals(true, numA.equals(numB));
85 assertEquals(true, numB.equals(numA));
86 assertEquals(true, numB.equals(numB));
87 assertEquals(false, numA.equals(numC));
88 assertEquals(false, numB.equals(numC));
89 assertEquals(true, numC.equals(numC));
90 assertEquals(false, numA.equals(null));
91 assertEquals(false, numA.equals(Integer.valueOf(0)));
92 assertEquals(false, numA.equals("0"));
93 }
94
86 assertTrue(numA.equals(numA));
87 assertTrue(numA.equals(numB));
88 assertTrue(numB.equals(numA));
89 assertTrue(numB.equals(numB));
90 assertFalse(numA.equals(numC));
91 assertFalse(numB.equals(numC));
92 assertTrue(numC.equals(numC));
93 assertFalse(numA.equals(null));
94 assertFalse(numA.equals(Integer.valueOf(0)));
95 assertFalse(numA.equals("0"));
96 }
97
98 @Test
9599 public void testHashCode() {
96100 final MutableInt mutNumA = new MutableInt(0);
97101 final MutableInt mutNumB = new MutableInt(0);
98102 final MutableInt mutNumC = new MutableInt(1);
99103
100 assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode());
101 assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode());
102 assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode());
103 assertEquals(true, mutNumA.hashCode() == Integer.valueOf(0).hashCode());
104 }
105
104 assertTrue(mutNumA.hashCode() == mutNumA.hashCode());
105 assertTrue(mutNumA.hashCode() == mutNumB.hashCode());
106 assertFalse(mutNumA.hashCode() == mutNumC.hashCode());
107 assertTrue(mutNumA.hashCode() == Integer.valueOf(0).hashCode());
108 }
109
110 @Test
106111 public void testCompareTo() {
107112 final MutableInt mutNum = new MutableInt(0);
108113
109114 assertEquals(0, mutNum.compareTo(new MutableInt(0)));
110115 assertEquals(+1, mutNum.compareTo(new MutableInt(-1)));
111116 assertEquals(-1, mutNum.compareTo(new MutableInt(1)));
112 try {
113 mutNum.compareTo(null);
114 fail();
115 } catch (NullPointerException ex) {}
116 }
117
117 }
118
119 @Test(expected=NullPointerException.class)
120 public void testCompareToNull() {
121 final MutableInt mutNum = new MutableInt(0);
122 mutNum.compareTo(null);
123 }
124
125 @Test
118126 public void testPrimitiveValues() {
119 MutableInt mutNum = new MutableInt(1);
127 final MutableInt mutNum = new MutableInt(1);
120128
121129 assertEquals( (byte) 1, mutNum.byteValue() );
122130 assertEquals( (short) 1, mutNum.shortValue() );
125133 assertEquals( 1L, mutNum.longValue() );
126134 }
127135
136 @Test
128137 public void testToInteger() {
129138 assertEquals(Integer.valueOf(0), new MutableInt(0).toInteger());
130139 assertEquals(Integer.valueOf(123), new MutableInt(123).toInteger());
131140 }
132141
142 @Test
133143 public void testIncrement() {
134 MutableInt mutNum = new MutableInt(1);
144 final MutableInt mutNum = new MutableInt(1);
135145 mutNum.increment();
136146
137147 assertEquals(2, mutNum.intValue());
138148 assertEquals(2L, mutNum.longValue());
139149 }
140150
151 @Test
141152 public void testDecrement() {
142 MutableInt mutNum = new MutableInt(1);
153 final MutableInt mutNum = new MutableInt(1);
143154 mutNum.decrement();
144155
145156 assertEquals(0, mutNum.intValue());
146157 assertEquals(0L, mutNum.longValue());
147158 }
148159
160 @Test
149161 public void testAddValuePrimitive() {
150 MutableInt mutNum = new MutableInt(1);
162 final MutableInt mutNum = new MutableInt(1);
151163 mutNum.add(1);
152164
153165 assertEquals(2, mutNum.intValue());
154166 assertEquals(2L, mutNum.longValue());
155167 }
156168
169 @Test
157170 public void testAddValueObject() {
158 MutableInt mutNum = new MutableInt(1);
171 final MutableInt mutNum = new MutableInt(1);
159172 mutNum.add(Integer.valueOf(1));
160173
161174 assertEquals(2, mutNum.intValue());
162175 assertEquals(2L, mutNum.longValue());
163176 }
164177
178 @Test
165179 public void testSubtractValuePrimitive() {
166 MutableInt mutNum = new MutableInt(1);
180 final MutableInt mutNum = new MutableInt(1);
167181 mutNum.subtract(1);
168182
169183 assertEquals(0, mutNum.intValue());
170184 assertEquals(0L, mutNum.longValue());
171185 }
172186
187 @Test
173188 public void testSubtractValueObject() {
174 MutableInt mutNum = new MutableInt(1);
189 final MutableInt mutNum = new MutableInt(1);
175190 mutNum.subtract(Integer.valueOf(1));
176191
177192 assertEquals(0, mutNum.intValue());
178193 assertEquals(0L, mutNum.longValue());
179194 }
180195
196 @Test
181197 public void testToString() {
182198 assertEquals("0", new MutableInt(0).toString());
183199 assertEquals("10", new MutableInt(10).toString());
1515 */
1616 package org.apache.commons.lang3.mutable;
1717
18 import junit.framework.TestCase;
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1920
2021 /**
2122 * JUnit tests.
2223 *
23 * @version $Id: MutableLongTest.java 1153487 2011-08-03 13:44:51Z ggregory $
24 * @version $Id: MutableLongTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2425 * @see MutableLong
2526 */
26 public class MutableLongTest extends TestCase {
27
28 public MutableLongTest(String testName) {
29 super(testName);
30 }
27 public class MutableLongTest {
3128
3229 // ----------------------------------------------------------------
30 @Test
3331 public void testConstructors() {
3432 assertEquals(0, new MutableLong().longValue());
3533
4038
4139 assertEquals(2, new MutableLong("2").longValue());
4240
43 try {
44 new MutableLong((Number)null);
45 fail();
46 } catch (NullPointerException ex) {}
4741 }
4842
43 @Test(expected=NullPointerException.class)
44 public void testConstructorNull() {
45 new MutableLong((Number)null);
46 }
47
48 @Test
4949 public void testGetSet() {
5050 final MutableLong mutNum = new MutableLong(0);
5151 assertEquals(0, new MutableLong().longValue());
6262 mutNum.setValue(new MutableLong(3));
6363 assertEquals(3, mutNum.longValue());
6464 assertEquals(Long.valueOf(3), mutNum.getValue());
65 try {
66 mutNum.setValue(null);
67 fail();
68 } catch (NullPointerException ex) {}
6965 }
7066
67 @Test(expected=NullPointerException.class)
68 public void testSetNull() {
69 final MutableLong mutNum = new MutableLong(0);
70 mutNum.setValue(null);
71 }
72
73 @Test
7174 public void testEquals() {
7275 final MutableLong mutNumA = new MutableLong(0);
7376 final MutableLong mutNumB = new MutableLong(0);
7477 final MutableLong mutNumC = new MutableLong(1);
7578
76 assertEquals(true, mutNumA.equals(mutNumA));
77 assertEquals(true, mutNumA.equals(mutNumB));
78 assertEquals(true, mutNumB.equals(mutNumA));
79 assertEquals(true, mutNumB.equals(mutNumB));
80 assertEquals(false, mutNumA.equals(mutNumC));
81 assertEquals(false, mutNumB.equals(mutNumC));
82 assertEquals(true, mutNumC.equals(mutNumC));
83 assertEquals(false, mutNumA.equals(null));
84 assertEquals(false, mutNumA.equals(Long.valueOf(0)));
85 assertEquals(false, mutNumA.equals("0"));
79 assertTrue(mutNumA.equals(mutNumA));
80 assertTrue(mutNumA.equals(mutNumB));
81 assertTrue(mutNumB.equals(mutNumA));
82 assertTrue(mutNumB.equals(mutNumB));
83 assertFalse(mutNumA.equals(mutNumC));
84 assertFalse(mutNumB.equals(mutNumC));
85 assertTrue(mutNumC.equals(mutNumC));
86 assertFalse(mutNumA.equals(null));
87 assertFalse(mutNumA.equals(Long.valueOf(0)));
88 assertFalse(mutNumA.equals("0"));
8689 }
8790
91 @Test
8892 public void testHashCode() {
8993 final MutableLong mutNumA = new MutableLong(0);
9094 final MutableLong mutNumB = new MutableLong(0);
9195 final MutableLong mutNumC = new MutableLong(1);
9296
93 assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode());
94 assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode());
95 assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode());
96 assertEquals(true, mutNumA.hashCode() == Long.valueOf(0).hashCode());
97 assertTrue(mutNumA.hashCode() == mutNumA.hashCode());
98 assertTrue(mutNumA.hashCode() == mutNumB.hashCode());
99 assertFalse(mutNumA.hashCode() == mutNumC.hashCode());
100 assertTrue(mutNumA.hashCode() == Long.valueOf(0).hashCode());
97101 }
98102
103 @Test
99104 public void testCompareTo() {
100105 final MutableLong mutNum = new MutableLong(0);
101106
102107 assertEquals(0, mutNum.compareTo(new MutableLong(0)));
103108 assertEquals(+1, mutNum.compareTo(new MutableLong(-1)));
104109 assertEquals(-1, mutNum.compareTo(new MutableLong(1)));
105 try {
106 mutNum.compareTo(null);
107 fail();
108 } catch (NullPointerException ex) {}
109110 }
110111
112 @Test(expected=NullPointerException.class)
113 public void testCompareToNull() {
114 final MutableLong mutNum = new MutableLong(0);
115 mutNum.compareTo(null);
116 }
117
118 @Test
111119 public void testPrimitiveValues() {
112 MutableLong mutNum = new MutableLong(1L);
120 final MutableLong mutNum = new MutableLong(1L);
113121
114122 assertEquals( 1.0F, mutNum.floatValue(), 0 );
115123 assertEquals( 1.0, mutNum.doubleValue(), 0 );
119127 assertEquals( 1L, mutNum.longValue() );
120128 }
121129
130 @Test
122131 public void testToLong() {
123132 assertEquals(Long.valueOf(0L), new MutableLong(0L).toLong());
124133 assertEquals(Long.valueOf(123L), new MutableLong(123L).toLong());
125134 }
126135
136 @Test
127137 public void testIncrement() {
128 MutableLong mutNum = new MutableLong(1);
138 final MutableLong mutNum = new MutableLong(1);
129139 mutNum.increment();
130140
131141 assertEquals(2, mutNum.intValue());
132142 assertEquals(2L, mutNum.longValue());
133143 }
134144
145 @Test
135146 public void testDecrement() {
136 MutableLong mutNum = new MutableLong(1);
147 final MutableLong mutNum = new MutableLong(1);
137148 mutNum.decrement();
138149
139150 assertEquals(0, mutNum.intValue());
140151 assertEquals(0L, mutNum.longValue());
141152 }
142153
154 @Test
143155 public void testAddValuePrimitive() {
144 MutableLong mutNum = new MutableLong(1);
156 final MutableLong mutNum = new MutableLong(1);
145157 mutNum.add(1);
146158
147159 assertEquals(2, mutNum.intValue());
148160 assertEquals(2L, mutNum.longValue());
149161 }
150162
163 @Test
151164 public void testAddValueObject() {
152 MutableLong mutNum = new MutableLong(1);
165 final MutableLong mutNum = new MutableLong(1);
153166 mutNum.add(Long.valueOf(1));
154167
155168 assertEquals(2, mutNum.intValue());
156169 assertEquals(2L, mutNum.longValue());
157170 }
158171
172 @Test
159173 public void testSubtractValuePrimitive() {
160 MutableLong mutNum = new MutableLong(1);
174 final MutableLong mutNum = new MutableLong(1);
161175 mutNum.subtract(1);
162176
163177 assertEquals(0, mutNum.intValue());
164178 assertEquals(0L, mutNum.longValue());
165179 }
166180
181 @Test
167182 public void testSubtractValueObject() {
168 MutableLong mutNum = new MutableLong(1);
183 final MutableLong mutNum = new MutableLong(1);
169184 mutNum.subtract(Long.valueOf(1));
170185
171186 assertEquals(0, mutNum.intValue());
172187 assertEquals(0L, mutNum.longValue());
173188 }
174189
190 @Test
175191 public void testToString() {
176192 assertEquals("0", new MutableLong(0).toString());
177193 assertEquals("10", new MutableLong(10).toString());
1515 */
1616 package org.apache.commons.lang3.mutable;
1717
18 import junit.framework.TestCase;
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1920
2021 /**
2122 * JUnit tests.
2223 *
23 * @version $Id: MutableObjectTest.java 1153490 2011-08-03 13:53:35Z ggregory $
24 * @version $Id: MutableObjectTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2425 * @see MutableShort
2526 */
26 public class MutableObjectTest extends TestCase {
27
28 public MutableObjectTest(String testName) {
29 super(testName);
30 }
27 public class MutableObjectTest {
3128
3229 // ----------------------------------------------------------------
30 @Test
3331 public void testConstructors() {
3432 assertEquals(null, new MutableObject<String>().getValue());
3533
36 Integer i = Integer.valueOf(6);
34 final Integer i = Integer.valueOf(6);
3735 assertSame(i, new MutableObject<Integer>(i).getValue());
3836 assertSame("HI", new MutableObject<String>("HI").getValue());
3937 assertSame(null, new MutableObject<Object>(null).getValue());
4038 }
4139
40 @Test
4241 public void testGetSet() {
4342 final MutableObject<String> mutNum = new MutableObject<String>();
4443 assertEquals(null, new MutableObject<Object>().getValue());
5049 assertSame(null, mutNum.getValue());
5150 }
5251
52 @Test
5353 public void testEquals() {
5454 final MutableObject<String> mutNumA = new MutableObject<String>("ALPHA");
5555 final MutableObject<String> mutNumB = new MutableObject<String>("ALPHA");
5656 final MutableObject<String> mutNumC = new MutableObject<String>("BETA");
5757 final MutableObject<String> mutNumD = new MutableObject<String>(null);
5858
59 assertEquals(true, mutNumA.equals(mutNumA));
60 assertEquals(true, mutNumA.equals(mutNumB));
61 assertEquals(true, mutNumB.equals(mutNumA));
62 assertEquals(true, mutNumB.equals(mutNumB));
63 assertEquals(false, mutNumA.equals(mutNumC));
64 assertEquals(false, mutNumB.equals(mutNumC));
65 assertEquals(true, mutNumC.equals(mutNumC));
66 assertEquals(false, mutNumA.equals(mutNumD));
67 assertEquals(true, mutNumD.equals(mutNumD));
59 assertTrue(mutNumA.equals(mutNumA));
60 assertTrue(mutNumA.equals(mutNumB));
61 assertTrue(mutNumB.equals(mutNumA));
62 assertTrue(mutNumB.equals(mutNumB));
63 assertFalse(mutNumA.equals(mutNumC));
64 assertFalse(mutNumB.equals(mutNumC));
65 assertTrue(mutNumC.equals(mutNumC));
66 assertFalse(mutNumA.equals(mutNumD));
67 assertTrue(mutNumD.equals(mutNumD));
6868
69 assertEquals(false, mutNumA.equals(null));
70 assertEquals(false, mutNumA.equals(new Object()));
71 assertEquals(false, mutNumA.equals("0"));
69 assertFalse(mutNumA.equals(null));
70 assertFalse(mutNumA.equals(new Object()));
71 assertFalse(mutNumA.equals("0"));
7272 }
7373
74 @Test
7475 public void testHashCode() {
7576 final MutableObject<String> mutNumA = new MutableObject<String>("ALPHA");
7677 final MutableObject<String> mutNumB = new MutableObject<String>("ALPHA");
7778 final MutableObject<String> mutNumC = new MutableObject<String>("BETA");
7879 final MutableObject<String> mutNumD = new MutableObject<String>(null);
7980
80 assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode());
81 assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode());
82 assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode());
83 assertEquals(false, mutNumA.hashCode() == mutNumD.hashCode());
84 assertEquals(true, mutNumA.hashCode() == "ALPHA".hashCode());
81 assertTrue(mutNumA.hashCode() == mutNumA.hashCode());
82 assertTrue(mutNumA.hashCode() == mutNumB.hashCode());
83 assertFalse(mutNumA.hashCode() == mutNumC.hashCode());
84 assertFalse(mutNumA.hashCode() == mutNumD.hashCode());
85 assertTrue(mutNumA.hashCode() == "ALPHA".hashCode());
8586 assertEquals(0, mutNumD.hashCode());
8687 }
8788
89 @Test
8890 public void testToString() {
8991 assertEquals("HI", new MutableObject<String>("HI").toString());
9092 assertEquals("10.0", new MutableObject<Double>(Double.valueOf(10)).toString());
1515 */
1616 package org.apache.commons.lang3.mutable;
1717
18 import junit.framework.TestCase;
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1920
2021 /**
2122 * JUnit tests.
2223 *
23 * @version $Id: MutableShortTest.java 1153488 2011-08-03 13:47:49Z ggregory $
24 * @version $Id: MutableShortTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2425 * @see MutableShort
2526 */
26 public class MutableShortTest extends TestCase {
27
28 public MutableShortTest(String testName) {
29 super(testName);
30 }
27 public class MutableShortTest {
3128
3229 // ----------------------------------------------------------------
30 @Test
3331 public void testConstructors() {
3432 assertEquals((short) 0, new MutableShort().shortValue());
3533
4341 try {
4442 new MutableShort((Number)null);
4543 fail();
46 } catch (NullPointerException ex) {}
44 } catch (final NullPointerException ex) {}
4745 }
4846
47 @Test
4948 public void testGetSet() {
5049 final MutableShort mutNum = new MutableShort((short) 0);
5150 assertEquals((short) 0, new MutableShort().shortValue());
6564 try {
6665 mutNum.setValue(null);
6766 fail();
68 } catch (NullPointerException ex) {}
67 } catch (final NullPointerException ex) {}
6968 }
7069
70 @Test
7171 public void testEquals() {
7272 final MutableShort mutNumA = new MutableShort((short) 0);
7373 final MutableShort mutNumB = new MutableShort((short) 0);
7474 final MutableShort mutNumC = new MutableShort((short) 1);
7575
76 assertEquals(true, mutNumA.equals(mutNumA));
77 assertEquals(true, mutNumA.equals(mutNumB));
78 assertEquals(true, mutNumB.equals(mutNumA));
79 assertEquals(true, mutNumB.equals(mutNumB));
80 assertEquals(false, mutNumA.equals(mutNumC));
81 assertEquals(false, mutNumB.equals(mutNumC));
82 assertEquals(true, mutNumC.equals(mutNumC));
83 assertEquals(false, mutNumA.equals(null));
84 assertEquals(false, mutNumA.equals(Short.valueOf((short) 0)));
85 assertEquals(false, mutNumA.equals("0"));
76 assertTrue(mutNumA.equals(mutNumA));
77 assertTrue(mutNumA.equals(mutNumB));
78 assertTrue(mutNumB.equals(mutNumA));
79 assertTrue(mutNumB.equals(mutNumB));
80 assertFalse(mutNumA.equals(mutNumC));
81 assertFalse(mutNumB.equals(mutNumC));
82 assertTrue(mutNumC.equals(mutNumC));
83 assertFalse(mutNumA.equals(null));
84 assertFalse(mutNumA.equals(Short.valueOf((short) 0)));
85 assertFalse(mutNumA.equals("0"));
8686 }
8787
88 @Test
8889 public void testHashCode() {
8990 final MutableShort mutNumA = new MutableShort((short) 0);
9091 final MutableShort mutNumB = new MutableShort((short) 0);
9192 final MutableShort mutNumC = new MutableShort((short) 1);
9293
93 assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode());
94 assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode());
95 assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode());
96 assertEquals(true, mutNumA.hashCode() == Short.valueOf((short) 0).hashCode());
94 assertTrue(mutNumA.hashCode() == mutNumA.hashCode());
95 assertTrue(mutNumA.hashCode() == mutNumB.hashCode());
96 assertFalse(mutNumA.hashCode() == mutNumC.hashCode());
97 assertTrue(mutNumA.hashCode() == Short.valueOf((short) 0).hashCode());
9798 }
9899
100 @Test
99101 public void testCompareTo() {
100102 final MutableShort mutNum = new MutableShort((short) 0);
101103
105107 try {
106108 mutNum.compareTo(null);
107109 fail();
108 } catch (NullPointerException ex) {}
110 } catch (final NullPointerException ex) {}
109111 }
110112
113 @Test
111114 public void testPrimitiveValues() {
112 MutableShort mutNum = new MutableShort( (short) 1 );
115 final MutableShort mutNum = new MutableShort( (short) 1 );
113116
114117 assertEquals( 1.0F, mutNum.floatValue(), 0 );
115118 assertEquals( 1.0, mutNum.doubleValue(), 0 );
119122 assertEquals( 1L, mutNum.longValue() );
120123 }
121124
125 @Test
122126 public void testToShort() {
123127 assertEquals(Short.valueOf((short) 0), new MutableShort((short) 0).toShort());
124128 assertEquals(Short.valueOf((short) 123), new MutableShort((short) 123).toShort());
125129 }
126130
131 @Test
127132 public void testIncrement() {
128 MutableShort mutNum = new MutableShort((short) 1);
133 final MutableShort mutNum = new MutableShort((short) 1);
129134 mutNum.increment();
130135
131136 assertEquals(2, mutNum.intValue());
132137 assertEquals(2L, mutNum.longValue());
133138 }
134139
140 @Test
135141 public void testDecrement() {
136 MutableShort mutNum = new MutableShort((short) 1);
142 final MutableShort mutNum = new MutableShort((short) 1);
137143 mutNum.decrement();
138144
139145 assertEquals(0, mutNum.intValue());
140146 assertEquals(0L, mutNum.longValue());
141147 }
142148
149 @Test
143150 public void testAddValuePrimitive() {
144 MutableShort mutNum = new MutableShort((short) 1);
151 final MutableShort mutNum = new MutableShort((short) 1);
145152 mutNum.add((short) 1);
146153
147154 assertEquals((short) 2, mutNum.shortValue());
148155 }
149156
157 @Test
150158 public void testAddValueObject() {
151 MutableShort mutNum = new MutableShort((short) 1);
159 final MutableShort mutNum = new MutableShort((short) 1);
152160 mutNum.add(Short.valueOf((short) 1));
153161
154162 assertEquals((short) 2, mutNum.shortValue());
155163 }
156164
165 @Test
157166 public void testSubtractValuePrimitive() {
158 MutableShort mutNum = new MutableShort((short) 1);
167 final MutableShort mutNum = new MutableShort((short) 1);
159168 mutNum.subtract((short) 1);
160169
161170 assertEquals((short) 0, mutNum.shortValue());
162171 }
163172
173 @Test
164174 public void testSubtractValueObject() {
165 MutableShort mutNum = new MutableShort((short) 1);
175 final MutableShort mutNum = new MutableShort((short) 1);
166176 mutNum.subtract(Short.valueOf((short) 1));
167177
168178 assertEquals((short) 0, mutNum.shortValue());
169179 }
170180
181 @Test
171182 public void testToString() {
172183 assertEquals("0", new MutableShort((short) 0).toString());
173184 assertEquals("10", new MutableShort((short) 10).toString());
1515 */
1616 package org.apache.commons.lang3.reflect;
1717
18 import org.junit.Test;
19 import org.junit.Before;
20 import static org.junit.Assert.*;
1821 import java.lang.reflect.Constructor;
1922 import java.util.Arrays;
2023 import java.util.HashMap;
2124 import java.util.Map;
2225
23 import junit.framework.TestCase;
24
2526 import org.apache.commons.lang3.ArrayUtils;
2627 import org.apache.commons.lang3.math.NumberUtils;
28 import org.apache.commons.lang3.mutable.MutableObject;
2729
2830 /**
2931 * Unit tests ConstructorUtils
30 * @version $Id: ConstructorUtilsTest.java 1097487 2011-04-28 14:49:45Z ggregory $
32 * @version $Id: ConstructorUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3133 */
32 public class ConstructorUtilsTest extends TestCase {
34 public class ConstructorUtilsTest {
3335 public static class TestBean {
34 private String toString;
36 private final String toString;
3537
3638 public TestBean() {
3739 toString = "()";
3840 }
3941
40 public TestBean(int i) {
42 public TestBean(final int i) {
4143 toString = "(int)";
4244 }
4345
44 public TestBean(Integer i) {
46 public TestBean(final Integer i) {
4547 toString = "(Integer)";
4648 }
4749
48 public TestBean(double d) {
50 public TestBean(final double d) {
4951 toString = "(double)";
5052 }
5153
52 public TestBean(String s) {
54 public TestBean(final String s) {
5355 toString = "(String)";
5456 }
5557
56 public TestBean(Object o) {
58 public TestBean(final Object o) {
5759 toString = "(Object)";
5860 }
5961
6971 }
7072 }
7173
72 private Map<Class<?>, Class<?>[]> classCache;
73
74 public ConstructorUtilsTest(String name) {
75 super(name);
74 private final Map<Class<?>, Class<?>[]> classCache;
75
76 public ConstructorUtilsTest() {
7677 classCache = new HashMap<Class<?>, Class<?>[]>();
7778 }
7879
79 @Override
80 protected void setUp() throws Exception {
81 super.setUp();
80
81 @Before
82 public void setUp() throws Exception {
8283 classCache.clear();
8384 }
8485
86 @Test
8587 public void testConstructor() throws Exception {
8688 assertNotNull(MethodUtils.class.newInstance());
8789 }
8890
91 @Test
8992 public void testInvokeConstructor() throws Exception {
9093 assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class,
9194 (Object[]) ArrayUtils.EMPTY_CLASS_ARRAY).toString());
108111 TestBean.class, NumberUtils.DOUBLE_ONE).toString());
109112 }
110113
114 @Test
111115 public void testInvokeExactConstructor() throws Exception {
112116 assertEquals("()", ConstructorUtils.invokeExactConstructor(
113117 TestBean.class, (Object[]) ArrayUtils.EMPTY_CLASS_ARRAY).toString());
127131 ConstructorUtils.invokeExactConstructor(TestBean.class,
128132 NumberUtils.BYTE_ONE);
129133 fail("should throw NoSuchMethodException");
130 } catch (NoSuchMethodException e) {
134 } catch (final NoSuchMethodException e) {
131135 }
132136 try {
133137 ConstructorUtils.invokeExactConstructor(TestBean.class,
134138 NumberUtils.LONG_ONE);
135139 fail("should throw NoSuchMethodException");
136 } catch (NoSuchMethodException e) {
140 } catch (final NoSuchMethodException e) {
137141 }
138142 try {
139143 ConstructorUtils.invokeExactConstructor(TestBean.class,
140144 Boolean.TRUE);
141145 fail("should throw NoSuchMethodException");
142 } catch (NoSuchMethodException e) {
143 }
144 }
145
146 } catch (final NoSuchMethodException e) {
147 }
148 }
149
150 @Test
146151 public void testGetAccessibleConstructor() throws Exception {
147152 assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class
148153 .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY)));
150155 .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY)));
151156 }
152157
158 @Test
153159 public void testGetAccessibleConstructorFromDescription() throws Exception {
154160 assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class,
155161 ArrayUtils.EMPTY_CLASS_ARRAY));
157163 PrivateClass.class, ArrayUtils.EMPTY_CLASS_ARRAY));
158164 }
159165
166 @Test
160167 public void testGetMatchingAccessibleMethod() throws Exception {
161168 expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
162169 ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_CLASS_ARRAY);
198205 singletonArray(Double.TYPE), singletonArray(Double.TYPE));
199206 }
200207
201 private void expectMatchingAccessibleConstructorParameterTypes(Class<?> cls,
202 Class<?>[] requestTypes, Class<?>[] actualTypes) {
203 Constructor<?> c = ConstructorUtils.getMatchingAccessibleConstructor(cls,
208 @Test
209 public void testNullArgument() {
210 expectMatchingAccessibleConstructorParameterTypes(MutableObject.class,
211 singletonArray(null), singletonArray(Object.class));
212 }
213
214 private void expectMatchingAccessibleConstructorParameterTypes(final Class<?> cls,
215 final Class<?>[] requestTypes, final Class<?>[] actualTypes) {
216 final Constructor<?> c = ConstructorUtils.getMatchingAccessibleConstructor(cls,
204217 requestTypes);
205218 assertTrue(toString(c.getParameterTypes()) + " not equals "
206219 + toString(actualTypes), Arrays.equals(actualTypes, c
207220 .getParameterTypes()));
208221 }
209222
210 private String toString(Class<?>[] c) {
223 private String toString(final Class<?>[] c) {
211224 return Arrays.asList(c).toString();
212225 }
213226
214 private Class<?>[] singletonArray(Class<?> c) {
227 private Class<?>[] singletonArray(final Class<?> c) {
215228 Class<?>[] result = classCache.get(c);
216229 if (result == null) {
217230 result = new Class[] { c };
1515 */
1616 package org.apache.commons.lang3.reflect;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertNull;
22 import static org.junit.Assert.assertTrue;
23 import static org.junit.Assert.fail;
24 import static org.junit.Assume.assumeNotNull;
18 import org.apache.commons.lang3.ArrayUtils;
19 import org.apache.commons.lang3.reflect.testbed.*;
20 import org.junit.Before;
21 import org.junit.Test;
2522
2623 import java.lang.reflect.Constructor;
2724 import java.lang.reflect.Field;
2825 import java.lang.reflect.Modifier;
29
30 import org.apache.commons.lang3.reflect.testbed.Ambig;
31 import org.apache.commons.lang3.reflect.testbed.Foo;
32 import org.apache.commons.lang3.reflect.testbed.PrivatelyShadowedChild;
33 import org.apache.commons.lang3.reflect.testbed.PublicChild;
34 import org.apache.commons.lang3.reflect.testbed.PubliclyShadowedChild;
35 import org.apache.commons.lang3.reflect.testbed.StaticContainer;
36 import org.apache.commons.lang3.reflect.testbed.StaticContainerChild;
37 import org.junit.Before;
38 import org.junit.Test;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29
30 import static org.junit.Assert.*;
31 import static org.junit.Assume.assumeNotNull;
3932
4033 /**
4134 * Unit tests FieldUtils
42 * @version $Id: FieldUtilsTest.java 1199724 2011-11-09 12:51:52Z sebb $
35 *
36 * @version $Id: FieldUtilsTest.java 1546799 2013-12-01 10:34:02Z mcucchiara $
4337 */
4438 public class FieldUtilsTest {
4539
46 static final String S = "s";
47 static final String SS = "ss";
4840 static final Integer I0 = Integer.valueOf(0);
4941 static final Integer I1 = Integer.valueOf(1);
5042 static final Double D0 = Double.valueOf(0.0);
5345 private PublicChild publicChild;
5446 private PubliclyShadowedChild publiclyShadowedChild;
5547 private PrivatelyShadowedChild privatelyShadowedChild;
56 private Class<?> parentClass = PublicChild.class.getSuperclass();
48 private final Class<?> parentClass = PublicChild.class.getSuperclass();
5749
5850 @Before
5951 public void setUp() {
6658 @Test
6759 public void testConstructor() {
6860 assertNotNull(new FieldUtils());
69 Constructor<?>[] cons = FieldUtils.class.getDeclaredConstructors();
61 final Constructor<?>[] cons = FieldUtils.class.getDeclaredConstructors();
7062 assertEquals(1, cons.length);
7163 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
7264 assertTrue(Modifier.isPublic(FieldUtils.class.getModifiers()));
7365 assertFalse(Modifier.isFinal(FieldUtils.class.getModifiers()));
7466 }
75
67
7668 @Test
7769 public void testGetField() {
7870 assertEquals(Foo.class, FieldUtils.getField(PublicChild.class, "VALUE").getDeclaringClass());
8173 assertNull(FieldUtils.getField(PublicChild.class, "i"));
8274 assertNull(FieldUtils.getField(PublicChild.class, "d"));
8375 assertEquals(Foo.class, FieldUtils.getField(PubliclyShadowedChild.class, "VALUE").getDeclaringClass());
84 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "s")
85 .getDeclaringClass());
86 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "b")
87 .getDeclaringClass());
88 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "i")
89 .getDeclaringClass());
90 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "d")
91 .getDeclaringClass());
76 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "s").getDeclaringClass());
77 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "b").getDeclaringClass());
78 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "i").getDeclaringClass());
79 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "d").getDeclaringClass());
9280 assertEquals(Foo.class, FieldUtils.getField(PrivatelyShadowedChild.class, "VALUE").getDeclaringClass());
9381 assertEquals(parentClass, FieldUtils.getField(PrivatelyShadowedChild.class, "s").getDeclaringClass());
9482 assertNull(FieldUtils.getField(PrivatelyShadowedChild.class, "b"));
9684 assertNull(FieldUtils.getField(PrivatelyShadowedChild.class, "d"));
9785 }
9886
99 @Test(expected=IllegalArgumentException.class)
87 @Test(expected = IllegalArgumentException.class)
10088 public void testGetFieldIllegalArgumentException1() {
10189 FieldUtils.getField(null, "none");
10290 }
103
104 @Test(expected=IllegalArgumentException.class)
91
92 @Test(expected = IllegalArgumentException.class)
10593 public void testGetFieldIllegalArgumentException2() {
10694 FieldUtils.getField(PublicChild.class, null);
10795 }
108
96
97 @Test(expected = IllegalArgumentException.class)
98 public void testGetFieldIllegalArgumentException3() {
99 FieldUtils.getField(PublicChild.class, "");
100 }
101
102 @Test(expected = IllegalArgumentException.class)
103 public void testGetFieldIllegalArgumentException4() {
104 FieldUtils.getField(PublicChild.class, " ");
105 }
106
109107 @Test
110108 public void testGetFieldForceAccess() {
111109 assertEquals(PublicChild.class, FieldUtils.getField(PublicChild.class, "VALUE", true).getDeclaringClass());
114112 assertEquals(parentClass, FieldUtils.getField(PublicChild.class, "i", true).getDeclaringClass());
115113 assertEquals(parentClass, FieldUtils.getField(PublicChild.class, "d", true).getDeclaringClass());
116114 assertEquals(Foo.class, FieldUtils.getField(PubliclyShadowedChild.class, "VALUE", true).getDeclaringClass());
117 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "s", true)
118 .getDeclaringClass());
119 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "b", true)
120 .getDeclaringClass());
121 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "i", true)
122 .getDeclaringClass());
123 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "d", true)
124 .getDeclaringClass());
115 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "s", true).getDeclaringClass());
116 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "b", true).getDeclaringClass());
117 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "i", true).getDeclaringClass());
118 assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "d", true).getDeclaringClass());
125119 assertEquals(Foo.class, FieldUtils.getField(PrivatelyShadowedChild.class, "VALUE", true).getDeclaringClass());
126 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "s", true)
127 .getDeclaringClass());
128 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "b", true)
129 .getDeclaringClass());
130 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "i", true)
131 .getDeclaringClass());
132 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "d", true)
133 .getDeclaringClass());
134 }
135
136 @Test(expected=IllegalArgumentException.class)
120 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "s", true).getDeclaringClass());
121 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "b", true).getDeclaringClass());
122 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "i", true).getDeclaringClass());
123 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "d", true).getDeclaringClass());
124 }
125
126 @Test(expected = IllegalArgumentException.class)
137127 public void testGetFieldForceAccessIllegalArgumentException1() {
138128 FieldUtils.getField(null, "none", true);
139129 }
140
141 @Test(expected=IllegalArgumentException.class)
130
131 @Test(expected = IllegalArgumentException.class)
142132 public void testGetFieldForceAccessIllegalArgumentException2() {
143133 FieldUtils.getField(PublicChild.class, null, true);
144 }
134 }
135
136 @Test(expected = IllegalArgumentException.class)
137 public void testGetFieldForceAccessIllegalArgumentException3() {
138 FieldUtils.getField(PublicChild.class, "", true);
139 }
140
141 @Test(expected = IllegalArgumentException.class)
142 public void testGetFieldForceAccessIllegalArgumentException4() {
143 FieldUtils.getField(PublicChild.class, " ", true);
144 }
145
146 @Test
147 public void testGetAllFields() {
148 assertArrayEquals(new Field[0], FieldUtils.getAllFields(Object.class));
149 final Field[] fieldsNumber = Number.class.getDeclaredFields();
150 assertArrayEquals(fieldsNumber, FieldUtils.getAllFields(Number.class));
151 final Field[] fieldsInteger = Integer.class.getDeclaredFields();
152 assertArrayEquals(ArrayUtils.addAll(fieldsInteger, fieldsNumber), FieldUtils.getAllFields(Integer.class));
153 assertEquals(5, FieldUtils.getAllFields(PublicChild.class).length);
154 }
155
156 @Test
157 public void testGetAllFieldsList() {
158 assertEquals(0, FieldUtils.getAllFieldsList(Object.class).size());
159 final List<Field> fieldsNumber = Arrays.asList(Number.class.getDeclaredFields());
160 assertEquals(fieldsNumber, FieldUtils.getAllFieldsList(Number.class));
161 final List<Field> fieldsInteger = Arrays.asList(Integer.class.getDeclaredFields());
162 final List<Field> allFieldsInteger = new ArrayList<Field>(fieldsInteger);
163 allFieldsInteger.addAll(fieldsNumber);
164 assertEquals(allFieldsInteger, FieldUtils.getAllFieldsList(Integer.class));
165 assertEquals(5, FieldUtils.getAllFieldsList(PublicChild.class).size());
166 }
145167
146168 @Test
147169 public void testGetDeclaredField() {
151173 assertNull(FieldUtils.getDeclaredField(PublicChild.class, "i"));
152174 assertNull(FieldUtils.getDeclaredField(PublicChild.class, "d"));
153175 assertNull(FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "VALUE"));
154 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "s")
155 .getDeclaringClass());
156 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "b")
157 .getDeclaringClass());
158 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "i")
159 .getDeclaringClass());
160 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "d")
161 .getDeclaringClass());
176 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "s").getDeclaringClass());
177 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "b").getDeclaringClass());
178 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "i").getDeclaringClass());
179 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "d").getDeclaringClass());
162180 assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "VALUE"));
163181 assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "s"));
164182 assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "b"));
166184 assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "d"));
167185 }
168186
169 @Test(expected=IllegalArgumentException.class)
187 @Test(expected = IllegalArgumentException.class)
170188 public void testGetDeclaredFieldAccessIllegalArgumentException1() {
171189 FieldUtils.getDeclaredField(null, "none");
172 }
173
174 @Test(expected=IllegalArgumentException.class)
190 }
191
192 @Test(expected = IllegalArgumentException.class)
175193 public void testGetDeclaredFieldAccessIllegalArgumentException2() {
176194 FieldUtils.getDeclaredField(PublicChild.class, null);
177 }
195 }
196
197 @Test(expected = IllegalArgumentException.class)
198 public void testGetDeclaredFieldAccessIllegalArgumentException3() {
199 FieldUtils.getDeclaredField(PublicChild.class, "");
200 }
201
202 @Test(expected = IllegalArgumentException.class)
203 public void testGetDeclaredFieldAccessIllegalArgumentException4() {
204 FieldUtils.getDeclaredField(PublicChild.class, " ");
205 }
178206
179207 @Test
180208 public void testGetDeclaredFieldForceAccess() {
181 assertEquals(PublicChild.class, FieldUtils.getDeclaredField(PublicChild.class, "VALUE", true)
182 .getDeclaringClass());
209 assertEquals(PublicChild.class, FieldUtils.getDeclaredField(PublicChild.class, "VALUE", true).getDeclaringClass());
183210 assertNull(FieldUtils.getDeclaredField(PublicChild.class, "s", true));
184211 assertNull(FieldUtils.getDeclaredField(PublicChild.class, "b", true));
185212 assertNull(FieldUtils.getDeclaredField(PublicChild.class, "i", true));
186213 assertNull(FieldUtils.getDeclaredField(PublicChild.class, "d", true));
187214 assertNull(FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "VALUE", true));
188 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "s", true)
189 .getDeclaringClass());
190 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "b", true)
191 .getDeclaringClass());
192 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "i", true)
193 .getDeclaringClass());
194 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "d", true)
195 .getDeclaringClass());
215 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "s", true).getDeclaringClass());
216 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "b", true).getDeclaringClass());
217 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "i", true).getDeclaringClass());
218 assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "d", true).getDeclaringClass());
196219 assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "VALUE", true));
197 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "s", true)
198 .getDeclaringClass());
199 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "b", true)
200 .getDeclaringClass());
201 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "i", true)
202 .getDeclaringClass());
203 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "d", true)
204 .getDeclaringClass());
205 }
206
207 @Test(expected=IllegalArgumentException.class)
220 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "s", true).getDeclaringClass());
221 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "b", true).getDeclaringClass());
222 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "i", true).getDeclaringClass());
223 assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "d", true).getDeclaringClass());
224 }
225
226 @Test(expected = IllegalArgumentException.class)
208227 public void testGetDeclaredFieldForceAccessIllegalArgumentException1() {
209228 FieldUtils.getDeclaredField(null, "none", true);
210 }
211
212 @Test(expected=IllegalArgumentException.class)
229 }
230
231 @Test(expected = IllegalArgumentException.class)
213232 public void testGetDeclaredFieldForceAccessIllegalArgumentException2() {
214233 FieldUtils.getDeclaredField(PublicChild.class, null, true);
215 }
234 }
235
236 @Test(expected = IllegalArgumentException.class)
237 public void testGetDeclaredFieldForceAccessIllegalArgumentException3() {
238 FieldUtils.getDeclaredField(PublicChild.class, "", true);
239 }
240
241 @Test(expected = IllegalArgumentException.class)
242 public void testGetDeclaredFieldForceAccessIllegalArgumentException4() {
243 FieldUtils.getDeclaredField(PublicChild.class, " ", true);
244 }
216245
217246 @Test
218247 public void testReadStaticField() throws Exception {
219248 assertEquals(Foo.VALUE, FieldUtils.readStaticField(FieldUtils.getField(Foo.class, "VALUE")));
220249 }
221250
222 @Test(expected=IllegalArgumentException.class)
251 @Test(expected = IllegalArgumentException.class)
223252 public void testReadStaticFieldIllegalArgumentException1() throws Exception {
224 FieldUtils.readStaticField(null);
225 }
226
227 @Test(expected=IllegalArgumentException.class)
253 FieldUtils.readStaticField(null);
254 }
255
256 @Test(expected = IllegalArgumentException.class)
228257 public void testReadStaticFieldIllegalArgumentException2() throws Exception {
229258 assertEquals(Foo.VALUE, FieldUtils.readStaticField(FieldUtils.getField(Foo.class, "VALUE")));
230 Field nonStaticField = FieldUtils.getField(PublicChild.class, "s");
259 final Field nonStaticField = FieldUtils.getField(PublicChild.class, "s");
231260 assumeNotNull(nonStaticField);
232261 FieldUtils.readStaticField(nonStaticField);
233262 }
238267 assertEquals(Foo.VALUE, FieldUtils.readStaticField(FieldUtils.getField(PublicChild.class, "VALUE")));
239268 }
240269
241 @Test(expected=IllegalArgumentException.class)
270 @Test(expected = IllegalArgumentException.class)
242271 public void testReadStaticFieldForceAccessIllegalArgumentException1() throws Exception {
243272 FieldUtils.readStaticField(null, true);
244273 }
245274
246 @Test(expected=IllegalArgumentException.class)
275 @Test(expected = IllegalArgumentException.class)
247276 public void testReadStaticFieldForceAccessIllegalArgumentException2() throws Exception {
248 Field nonStaticField = FieldUtils.getField(PublicChild.class, "s", true);
277 final Field nonStaticField = FieldUtils.getField(PublicChild.class, "s", true);
249278 assumeNotNull(nonStaticField);
250279 FieldUtils.readStaticField(nonStaticField);
251280 }
256285 assertEquals(Foo.VALUE, FieldUtils.readStaticField(PubliclyShadowedChild.class, "VALUE"));
257286 assertEquals(Foo.VALUE, FieldUtils.readStaticField(PrivatelyShadowedChild.class, "VALUE"));
258287 assertEquals(Foo.VALUE, FieldUtils.readStaticField(PublicChild.class, "VALUE"));
259
288
260289 try {
261290 FieldUtils.readStaticField(null, "none");
262291 fail("null class should cause an IllegalArgumentException");
263 } catch (IllegalArgumentException e) {
264 // expected
265 }
266
292 } catch (final IllegalArgumentException e) {
293 // expected
294 }
295
267296 try {
268297 FieldUtils.readStaticField(Foo.class, null);
269298 fail("null field name should cause an IllegalArgumentException");
270 } catch (IllegalArgumentException e) {
271 // expected
272 }
273
299 } catch (final IllegalArgumentException e) {
300 // expected
301 }
302
303 try {
304 FieldUtils.readStaticField(Foo.class, "");
305 fail("empty field name should cause an IllegalArgumentException");
306 } catch (final IllegalArgumentException e) {
307 // expected
308 }
309
310 try {
311 FieldUtils.readStaticField(Foo.class, " ");
312 fail("blank field name should cause an IllegalArgumentException");
313 } catch (final IllegalArgumentException e) {
314 // expected
315 }
316
274317 try {
275318 FieldUtils.readStaticField(Foo.class, "does_not_exist");
276319 fail("a field that doesn't exist should cause an IllegalArgumentException");
277 } catch (IllegalArgumentException e) {
278 // expected
279 }
280
320 } catch (final IllegalArgumentException e) {
321 // expected
322 }
323
281324 try {
282325 FieldUtils.readStaticField(PublicChild.class, "s");
283326 fail("non-static field should cause an IllegalArgumentException");
284 } catch (IllegalArgumentException e) {
327 } catch (final IllegalArgumentException e) {
285328 // expected
286329 }
287330 }
292335 assertEquals(Foo.VALUE, FieldUtils.readStaticField(PubliclyShadowedChild.class, "VALUE", true));
293336 assertEquals(Foo.VALUE, FieldUtils.readStaticField(PrivatelyShadowedChild.class, "VALUE", true));
294337 assertEquals("child", FieldUtils.readStaticField(PublicChild.class, "VALUE", true));
295
338
296339 try {
297340 FieldUtils.readStaticField(null, "none", true);
298341 fail("null class should cause an IllegalArgumentException");
299 } catch (IllegalArgumentException e) {
300 // expected
301 }
302
342 } catch (final IllegalArgumentException e) {
343 // expected
344 }
345
303346 try {
304347 FieldUtils.readStaticField(Foo.class, null, true);
305348 fail("null field name should cause an IllegalArgumentException");
306 } catch (IllegalArgumentException e) {
307 // expected
308 }
309
349 } catch (final IllegalArgumentException e) {
350 // expected
351 }
352
353 try {
354 FieldUtils.readStaticField(Foo.class, "", true);
355 fail("empty field name should cause an IllegalArgumentException");
356 } catch (final IllegalArgumentException e) {
357 // expected
358 }
359
360 try {
361 FieldUtils.readStaticField(Foo.class, " ", true);
362 fail("blank field name should cause an IllegalArgumentException");
363 } catch (final IllegalArgumentException e) {
364 // expected
365 }
366
310367 try {
311368 FieldUtils.readStaticField(Foo.class, "does_not_exist", true);
312369 fail("a field that doesn't exist should cause an IllegalArgumentException");
313 } catch (IllegalArgumentException e) {
314 // expected
315 }
316
370 } catch (final IllegalArgumentException e) {
371 // expected
372 }
373
317374 try {
318375 FieldUtils.readStaticField(PublicChild.class, "s", false);
319376 fail("non-static field should cause an IllegalArgumentException");
320 } catch (IllegalArgumentException e) {
377 } catch (final IllegalArgumentException e) {
321378 // expected
322379 }
323380 }
326383 public void testReadDeclaredNamedStaticField() throws Exception {
327384 assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(Foo.class, "VALUE"));
328385 try {
329 assertEquals("child", FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE"));
330 fail("expected IllegalArgumentException");
331 } catch (IllegalArgumentException e) {
332 // pass
333 }
334 try {
335 assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE"));
336 fail("expected IllegalArgumentException");
337 } catch (IllegalArgumentException e) {
338 // pass
339 }
340 try {
341 assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE"));
342 fail("expected IllegalArgumentException");
343 } catch (IllegalArgumentException e) {
386 FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE");
387 fail("expected IllegalArgumentException");
388 } catch (final IllegalArgumentException e) {
389 // pass
390 }
391 try {
392 FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE");
393 fail("expected IllegalArgumentException");
394 } catch (final IllegalArgumentException e) {
395 // pass
396 }
397 try {
398 FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE");
399 fail("expected IllegalArgumentException");
400 } catch (final IllegalArgumentException e) {
344401 // pass
345402 }
346403 }
350407 assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(Foo.class, "VALUE", true));
351408 assertEquals("child", FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE", true));
352409 try {
353 assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE", true));
354 fail("expected IllegalArgumentException");
355 } catch (IllegalArgumentException e) {
356 // pass
357 }
358 try {
359 assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE", true));
360 fail("expected IllegalArgumentException");
361 } catch (IllegalArgumentException e) {
410 FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE", true);
411 fail("expected IllegalArgumentException");
412 } catch (final IllegalArgumentException e) {
413 // pass
414 }
415 try {
416 FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE", true);
417 fail("expected IllegalArgumentException");
418 } catch (final IllegalArgumentException e) {
362419 // pass
363420 }
364421 }
365422
366423 @Test
367424 public void testReadField() throws Exception {
368 Field parentS = FieldUtils.getDeclaredField(parentClass, "s");
425 final Field parentS = FieldUtils.getDeclaredField(parentClass, "s");
369426 assertEquals("s", FieldUtils.readField(parentS, publicChild));
370427 assertEquals("s", FieldUtils.readField(parentS, publiclyShadowedChild));
371428 assertEquals("s", FieldUtils.readField(parentS, privatelyShadowedChild));
372 Field parentB = FieldUtils.getDeclaredField(parentClass, "b", true);
429 final Field parentB = FieldUtils.getDeclaredField(parentClass, "b", true);
373430 assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publicChild));
374431 assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publiclyShadowedChild));
375432 assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, privatelyShadowedChild));
376 Field parentI = FieldUtils.getDeclaredField(parentClass, "i", true);
433 final Field parentI = FieldUtils.getDeclaredField(parentClass, "i", true);
377434 assertEquals(I0, FieldUtils.readField(parentI, publicChild));
378435 assertEquals(I0, FieldUtils.readField(parentI, publiclyShadowedChild));
379436 assertEquals(I0, FieldUtils.readField(parentI, privatelyShadowedChild));
380 Field parentD = FieldUtils.getDeclaredField(parentClass, "d", true);
437 final Field parentD = FieldUtils.getDeclaredField(parentClass, "d", true);
381438 assertEquals(D0, FieldUtils.readField(parentD, publicChild));
382439 assertEquals(D0, FieldUtils.readField(parentD, publiclyShadowedChild));
383440 assertEquals(D0, FieldUtils.readField(parentD, privatelyShadowedChild));
384
385 try {
386 FieldUtils.readField((Field)null, publicChild);
441
442 try {
443 FieldUtils.readField(null, publicChild);
387444 fail("a null field should cause an IllegalArgumentException");
388 } catch (IllegalArgumentException e) {
445 } catch (final IllegalArgumentException e) {
389446 // expected
390447 }
391448 }
392449
393450 @Test
394451 public void testReadFieldForceAccess() throws Exception {
395 Field parentS = FieldUtils.getDeclaredField(parentClass, "s");
452 final Field parentS = FieldUtils.getDeclaredField(parentClass, "s");
396453 parentS.setAccessible(false);
397454 assertEquals("s", FieldUtils.readField(parentS, publicChild, true));
398455 assertEquals("s", FieldUtils.readField(parentS, publiclyShadowedChild, true));
399456 assertEquals("s", FieldUtils.readField(parentS, privatelyShadowedChild, true));
400 Field parentB = FieldUtils.getDeclaredField(parentClass, "b", true);
457 final Field parentB = FieldUtils.getDeclaredField(parentClass, "b", true);
401458 parentB.setAccessible(false);
402459 assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publicChild, true));
403460 assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publiclyShadowedChild, true));
404461 assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, privatelyShadowedChild, true));
405 Field parentI = FieldUtils.getDeclaredField(parentClass, "i", true);
462 final Field parentI = FieldUtils.getDeclaredField(parentClass, "i", true);
406463 parentI.setAccessible(false);
407464 assertEquals(I0, FieldUtils.readField(parentI, publicChild, true));
408465 assertEquals(I0, FieldUtils.readField(parentI, publiclyShadowedChild, true));
409466 assertEquals(I0, FieldUtils.readField(parentI, privatelyShadowedChild, true));
410 Field parentD = FieldUtils.getDeclaredField(parentClass, "d", true);
467 final Field parentD = FieldUtils.getDeclaredField(parentClass, "d", true);
411468 parentD.setAccessible(false);
412469 assertEquals(D0, FieldUtils.readField(parentD, publicChild, true));
413470 assertEquals(D0, FieldUtils.readField(parentD, publiclyShadowedChild, true));
414471 assertEquals(D0, FieldUtils.readField(parentD, privatelyShadowedChild, true));
415
416 try {
417 FieldUtils.readField((Field)null, publicChild, true);
472
473 try {
474 FieldUtils.readField(null, publicChild, true);
418475 fail("a null field should cause an IllegalArgumentException");
419 } catch (IllegalArgumentException e) {
476 } catch (final IllegalArgumentException e) {
420477 // expected
421478 }
422479 }
426483 assertEquals("s", FieldUtils.readField(publicChild, "s"));
427484 assertEquals("ss", FieldUtils.readField(publiclyShadowedChild, "s"));
428485 assertEquals("s", FieldUtils.readField(privatelyShadowedChild, "s"));
429
486
430487 try {
431488 FieldUtils.readField(publicChild, null);
432489 fail("a null field name should cause an IllegalArgumentException");
433 } catch (IllegalArgumentException e) {
434 // expected
435 }
436
437 try {
438 FieldUtils.readField((Object)null, "none");
490 } catch (final IllegalArgumentException e) {
491 // expected
492 }
493
494 try {
495 FieldUtils.readField(publicChild, "");
496 fail("an empty field name should cause an IllegalArgumentException");
497 } catch (final IllegalArgumentException e) {
498 // expected
499 }
500
501 try {
502 FieldUtils.readField(publicChild, " ");
503 fail("a blank field name should cause an IllegalArgumentException");
504 } catch (final IllegalArgumentException e) {
505 // expected
506 }
507
508 try {
509 FieldUtils.readField((Object) null, "none");
439510 fail("a null target should cause an IllegalArgumentException");
440 } catch (IllegalArgumentException e) {
441 // expected
442 }
443
444 try {
445 assertEquals(Boolean.FALSE, FieldUtils.readField(publicChild, "b"));
446 fail("expected IllegalArgumentException");
447 } catch (IllegalArgumentException e) {
511 } catch (final IllegalArgumentException e) {
512 // expected
513 }
514
515 try {
516 FieldUtils.readField(publicChild, "b");
517 fail("expected IllegalArgumentException");
518 } catch (final IllegalArgumentException e) {
448519 // pass
449520 }
450521 assertEquals(Boolean.TRUE, FieldUtils.readField(publiclyShadowedChild, "b"));
451522 try {
452 assertEquals(Boolean.FALSE, FieldUtils.readField(privatelyShadowedChild, "b"));
453 fail("expected IllegalArgumentException");
454 } catch (IllegalArgumentException e) {
455 // pass
456 }
457 try {
458 assertEquals(I0, FieldUtils.readField(publicChild, "i"));
459 fail("expected IllegalArgumentException");
460 } catch (IllegalArgumentException e) {
523 FieldUtils.readField(privatelyShadowedChild, "b");
524 fail("expected IllegalArgumentException");
525 } catch (final IllegalArgumentException e) {
526 // pass
527 }
528 try {
529 FieldUtils.readField(publicChild, "i");
530 fail("expected IllegalArgumentException");
531 } catch (final IllegalArgumentException e) {
461532 // pass
462533 }
463534 assertEquals(I1, FieldUtils.readField(publiclyShadowedChild, "i"));
464535 try {
465 assertEquals(I0, FieldUtils.readField(privatelyShadowedChild, "i"));
466 fail("expected IllegalArgumentException");
467 } catch (IllegalArgumentException e) {
468 // pass
469 }
470 try {
471 assertEquals(D0, FieldUtils.readField(publicChild, "d"));
472 fail("expected IllegalArgumentException");
473 } catch (IllegalArgumentException e) {
536 FieldUtils.readField(privatelyShadowedChild, "i");
537 fail("expected IllegalArgumentException");
538 } catch (final IllegalArgumentException e) {
539 // pass
540 }
541 try {
542 FieldUtils.readField(publicChild, "d");
543 fail("expected IllegalArgumentException");
544 } catch (final IllegalArgumentException e) {
474545 // pass
475546 }
476547 assertEquals(D1, FieldUtils.readField(publiclyShadowedChild, "d"));
477548 try {
478 assertEquals(D0, FieldUtils.readField(privatelyShadowedChild, "d"));
479 fail("expected IllegalArgumentException");
480 } catch (IllegalArgumentException e) {
549 FieldUtils.readField(privatelyShadowedChild, "d");
550 fail("expected IllegalArgumentException");
551 } catch (final IllegalArgumentException e) {
481552 // pass
482553 }
483554 }
496567 assertEquals(D0, FieldUtils.readField(publicChild, "d", true));
497568 assertEquals(D1, FieldUtils.readField(publiclyShadowedChild, "d", true));
498569 assertEquals(D1, FieldUtils.readField(privatelyShadowedChild, "d", true));
499
570
500571 try {
501572 FieldUtils.readField(publicChild, null, true);
502573 fail("a null field name should cause an IllegalArgumentException");
503 } catch (IllegalArgumentException e) {
504 // expected
505 }
506
507 try {
508 FieldUtils.readField((Object)null, "none", true);
574 } catch (final IllegalArgumentException e) {
575 // expected
576 }
577
578 try {
579 FieldUtils.readField(publicChild, "", true);
580 fail("an empty field name should cause an IllegalArgumentException");
581 } catch (final IllegalArgumentException e) {
582 // expected
583 }
584
585 try {
586 FieldUtils.readField(publicChild, " ", true);
587 fail("a blank field name should cause an IllegalArgumentException");
588 } catch (final IllegalArgumentException e) {
589 // expected
590 }
591
592 try {
593 FieldUtils.readField((Object) null, "none", true);
509594 fail("a null target should cause an IllegalArgumentException");
510 } catch (IllegalArgumentException e) {
595 } catch (final IllegalArgumentException e) {
511596 // expected
512597 }
513598 }
517602 try {
518603 FieldUtils.readDeclaredField(publicChild, null);
519604 fail("a null field name should cause an IllegalArgumentException");
520 } catch (IllegalArgumentException e) {
521 // expected
522 }
523
524 try {
525 FieldUtils.readDeclaredField((Object)null, "none");
605 } catch (final IllegalArgumentException e) {
606 // expected
607 }
608
609 try {
610 FieldUtils.readDeclaredField(publicChild, "");
611 fail("an empty field name should cause an IllegalArgumentException");
612 } catch (final IllegalArgumentException e) {
613 // expected
614 }
615
616 try {
617 FieldUtils.readDeclaredField(publicChild, " ");
618 fail("a blank field name should cause an IllegalArgumentException");
619 } catch (final IllegalArgumentException e) {
620 // expected
621 }
622
623 try {
624 FieldUtils.readDeclaredField(null, "none");
526625 fail("a null target should cause an IllegalArgumentException");
527 } catch (IllegalArgumentException e) {
528 // expected
529 }
530
531 try {
532 assertEquals("s", FieldUtils.readDeclaredField(publicChild, "s"));
533 fail("expected IllegalArgumentException");
534 } catch (IllegalArgumentException e) {
626 } catch (final IllegalArgumentException e) {
627 // expected
628 }
629
630 try {
631 FieldUtils.readDeclaredField(publicChild, "s");
632 fail("expected IllegalArgumentException");
633 } catch (final IllegalArgumentException e) {
535634 // pass
536635 }
537636 assertEquals("ss", FieldUtils.readDeclaredField(publiclyShadowedChild, "s"));
538637 try {
539 assertEquals("s", FieldUtils.readDeclaredField(privatelyShadowedChild, "s"));
540 fail("expected IllegalArgumentException");
541 } catch (IllegalArgumentException e) {
542 // pass
543 }
544 try {
545 assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(publicChild, "b"));
546 fail("expected IllegalArgumentException");
547 } catch (IllegalArgumentException e) {
638 FieldUtils.readDeclaredField(privatelyShadowedChild, "s");
639 fail("expected IllegalArgumentException");
640 } catch (final IllegalArgumentException e) {
641 // pass
642 }
643 try {
644 FieldUtils.readDeclaredField(publicChild, "b");
645 fail("expected IllegalArgumentException");
646 } catch (final IllegalArgumentException e) {
548647 // pass
549648 }
550649 assertEquals(Boolean.TRUE, FieldUtils.readDeclaredField(publiclyShadowedChild, "b"));
551650 try {
552 assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(privatelyShadowedChild, "b"));
553 fail("expected IllegalArgumentException");
554 } catch (IllegalArgumentException e) {
555 // pass
556 }
557 try {
558 assertEquals(I0, FieldUtils.readDeclaredField(publicChild, "i"));
559 fail("expected IllegalArgumentException");
560 } catch (IllegalArgumentException e) {
651 FieldUtils.readDeclaredField(privatelyShadowedChild, "b");
652 fail("expected IllegalArgumentException");
653 } catch (final IllegalArgumentException e) {
654 // pass
655 }
656 try {
657 FieldUtils.readDeclaredField(publicChild, "i");
658 fail("expected IllegalArgumentException");
659 } catch (final IllegalArgumentException e) {
561660 // pass
562661 }
563662 assertEquals(I1, FieldUtils.readDeclaredField(publiclyShadowedChild, "i"));
564663 try {
565 assertEquals(I0, FieldUtils.readDeclaredField(privatelyShadowedChild, "i"));
566 fail("expected IllegalArgumentException");
567 } catch (IllegalArgumentException e) {
568 // pass
569 }
570 try {
571 assertEquals(D0, FieldUtils.readDeclaredField(publicChild, "d"));
572 fail("expected IllegalArgumentException");
573 } catch (IllegalArgumentException e) {
664 FieldUtils.readDeclaredField(privatelyShadowedChild, "i");
665 fail("expected IllegalArgumentException");
666 } catch (final IllegalArgumentException e) {
667 // pass
668 }
669 try {
670 FieldUtils.readDeclaredField(publicChild, "d");
671 fail("expected IllegalArgumentException");
672 } catch (final IllegalArgumentException e) {
574673 // pass
575674 }
576675 assertEquals(D1, FieldUtils.readDeclaredField(publiclyShadowedChild, "d"));
577676 try {
578 assertEquals(D0, FieldUtils.readDeclaredField(privatelyShadowedChild, "d"));
579 fail("expected IllegalArgumentException");
580 } catch (IllegalArgumentException e) {
677 FieldUtils.readDeclaredField(privatelyShadowedChild, "d");
678 fail("expected IllegalArgumentException");
679 } catch (final IllegalArgumentException e) {
581680 // pass
582681 }
583682 }
587686 try {
588687 FieldUtils.readDeclaredField(publicChild, null, true);
589688 fail("a null field name should cause an IllegalArgumentException");
590 } catch (IllegalArgumentException e) {
591 // expected
592 }
593
594 try {
595 FieldUtils.readDeclaredField((Object)null, "none", true);
689 } catch (final IllegalArgumentException e) {
690 // expected
691 }
692
693 try {
694 FieldUtils.readDeclaredField(publicChild, "", true);
695 fail("an empty field name should cause an IllegalArgumentException");
696 } catch (final IllegalArgumentException e) {
697 // expected
698 }
699
700 try {
701 FieldUtils.readDeclaredField(publicChild, " ", true);
702 fail("a blank field name should cause an IllegalArgumentException");
703 } catch (final IllegalArgumentException e) {
704 // expected
705 }
706
707 try {
708 FieldUtils.readDeclaredField(null, "none", true);
596709 fail("a null target should cause an IllegalArgumentException");
597 } catch (IllegalArgumentException e) {
598 // expected
599 }
600
601 try {
602 assertEquals("s", FieldUtils.readDeclaredField(publicChild, "s", true));
603 fail("expected IllegalArgumentException");
604 } catch (IllegalArgumentException e) {
710 } catch (final IllegalArgumentException e) {
711 // expected
712 }
713
714 try {
715 FieldUtils.readDeclaredField(publicChild, "s", true);
716 fail("expected IllegalArgumentException");
717 } catch (final IllegalArgumentException e) {
605718 // pass
606719 }
607720 assertEquals("ss", FieldUtils.readDeclaredField(publiclyShadowedChild, "s", true));
608721 assertEquals("ss", FieldUtils.readDeclaredField(privatelyShadowedChild, "s", true));
609722 try {
610 assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(publicChild, "b", true));
611 fail("expected IllegalArgumentException");
612 } catch (IllegalArgumentException e) {
723 FieldUtils.readDeclaredField(publicChild, "b", true);
724 fail("expected IllegalArgumentException");
725 } catch (final IllegalArgumentException e) {
613726 // pass
614727 }
615728 assertEquals(Boolean.TRUE, FieldUtils.readDeclaredField(publiclyShadowedChild, "b", true));
616729 assertEquals(Boolean.TRUE, FieldUtils.readDeclaredField(privatelyShadowedChild, "b", true));
617730 try {
618 assertEquals(I0, FieldUtils.readDeclaredField(publicChild, "i", true));
619 fail("expected IllegalArgumentException");
620 } catch (IllegalArgumentException e) {
731 FieldUtils.readDeclaredField(publicChild, "i", true);
732 fail("expected IllegalArgumentException");
733 } catch (final IllegalArgumentException e) {
621734 // pass
622735 }
623736 assertEquals(I1, FieldUtils.readDeclaredField(publiclyShadowedChild, "i", true));
624737 assertEquals(I1, FieldUtils.readDeclaredField(privatelyShadowedChild, "i", true));
625738 try {
626 assertEquals(D0, FieldUtils.readDeclaredField(publicChild, "d", true));
627 fail("expected IllegalArgumentException");
628 } catch (IllegalArgumentException e) {
739 FieldUtils.readDeclaredField(publicChild, "d", true);
740 fail("expected IllegalArgumentException");
741 } catch (final IllegalArgumentException e) {
629742 // pass
630743 }
631744 assertEquals(D1, FieldUtils.readDeclaredField(publiclyShadowedChild, "d", true));
641754 try {
642755 FieldUtils.writeStaticField(field, "new");
643756 fail("Expected IllegalAccessException");
644 } catch (IllegalAccessException e) {
757 } catch (final IllegalAccessException e) {
645758 // pass
646759 }
647760 field = StaticContainer.class.getDeclaredField("mutablePackage");
648761 try {
649762 FieldUtils.writeStaticField(field, "new");
650763 fail("Expected IllegalAccessException");
651 } catch (IllegalAccessException e) {
764 } catch (final IllegalAccessException e) {
652765 // pass
653766 }
654767 field = StaticContainer.class.getDeclaredField("mutablePrivate");
655768 try {
656769 FieldUtils.writeStaticField(field, "new");
657770 fail("Expected IllegalAccessException");
658 } catch (IllegalAccessException e) {
771 } catch (final IllegalAccessException e) {
659772 // pass
660773 }
661774 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PUBLIC");
662775 try {
663776 FieldUtils.writeStaticField(field, "new");
664777 fail("Expected IllegalAccessException");
665 } catch (IllegalAccessException e) {
778 } catch (final IllegalAccessException e) {
666779 // pass
667780 }
668781 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PROTECTED");
669782 try {
670783 FieldUtils.writeStaticField(field, "new");
671784 fail("Expected IllegalAccessException");
672 } catch (IllegalAccessException e) {
785 } catch (final IllegalAccessException e) {
673786 // pass
674787 }
675788 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PACKAGE");
676789 try {
677790 FieldUtils.writeStaticField(field, "new");
678791 fail("Expected IllegalAccessException");
679 } catch (IllegalAccessException e) {
792 } catch (final IllegalAccessException e) {
680793 // pass
681794 }
682795 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PRIVATE");
683796 try {
684797 FieldUtils.writeStaticField(field, "new");
685798 fail("Expected IllegalAccessException");
686 } catch (IllegalAccessException e) {
799 } catch (final IllegalAccessException e) {
687800 // pass
688801 }
689802 }
704817 assertEquals("new", StaticContainer.getMutablePrivate());
705818 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PUBLIC");
706819 try {
707 FieldUtils.writeStaticField(field, "new", true);
708 fail("Expected IllegalAccessException");
709 } catch (IllegalAccessException e) {
820 FieldUtils.writeStaticField(field, "new", true);
821 fail("Expected IllegalAccessException");
822 } catch (final IllegalAccessException e) {
710823 // pass
711824 }
712825 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PROTECTED");
713826 try {
714 FieldUtils.writeStaticField(field, "new", true);
715 fail("Expected IllegalAccessException");
716 } catch (IllegalAccessException e) {
827 FieldUtils.writeStaticField(field, "new", true);
828 fail("Expected IllegalAccessException");
829 } catch (final IllegalAccessException e) {
717830 // pass
718831 }
719832 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PACKAGE");
720833 try {
721 FieldUtils.writeStaticField(field, "new", true);
722 fail("Expected IllegalAccessException");
723 } catch (IllegalAccessException e) {
834 FieldUtils.writeStaticField(field, "new", true);
835 fail("Expected IllegalAccessException");
836 } catch (final IllegalAccessException e) {
724837 // pass
725838 }
726839 field = StaticContainer.class.getDeclaredField("IMMUTABLE_PRIVATE");
727840 try {
728 FieldUtils.writeStaticField(field, "new", true);
729 fail("Expected IllegalAccessException");
730 } catch (IllegalAccessException e) {
841 FieldUtils.writeStaticField(field, "new", true);
842 fail("Expected IllegalAccessException");
843 } catch (final IllegalAccessException e) {
731844 // pass
732845 }
733846 }
739852 try {
740853 FieldUtils.writeStaticField(StaticContainerChild.class, "mutableProtected", "new");
741854 fail("Expected IllegalArgumentException");
742 } catch (IllegalArgumentException e) {
855 } catch (final IllegalArgumentException e) {
743856 // pass
744857 }
745858 try {
746859 FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePackage", "new");
747860 fail("Expected IllegalArgumentException");
748 } catch (IllegalArgumentException e) {
861 } catch (final IllegalArgumentException e) {
749862 // pass
750863 }
751864 try {
752865 FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePrivate", "new");
753866 fail("Expected IllegalArgumentException");
754 } catch (IllegalArgumentException e) {
867 } catch (final IllegalArgumentException e) {
755868 // pass
756869 }
757870 try {
758871 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PUBLIC", "new");
759872 fail("Expected IllegalAccessException");
760 } catch (IllegalAccessException e) {
873 } catch (final IllegalAccessException e) {
761874 // pass
762875 }
763876 try {
764877 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PROTECTED", "new");
765878 fail("Expected IllegalArgumentException");
766 } catch (IllegalArgumentException e) {
879 } catch (final IllegalArgumentException e) {
767880 // pass
768881 }
769882 try {
770883 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PACKAGE", "new");
771884 fail("Expected IllegalArgumentException");
772 } catch (IllegalArgumentException e) {
885 } catch (final IllegalArgumentException e) {
773886 // pass
774887 }
775888 try {
776889 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PRIVATE", "new");
777890 fail("Expected IllegalArgumentException");
778 } catch (IllegalArgumentException e) {
891 } catch (final IllegalArgumentException e) {
779892 // pass
780893 }
781894 }
793906 try {
794907 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PUBLIC", "new", true);
795908 fail("Expected IllegalAccessException");
796 } catch (IllegalAccessException e) {
909 } catch (final IllegalAccessException e) {
797910 // pass
798911 }
799912 try {
800913 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PROTECTED", "new", true);
801914 fail("Expected IllegalAccessException");
802 } catch (IllegalAccessException e) {
915 } catch (final IllegalAccessException e) {
803916 // pass
804917 }
805918 try {
806919 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PACKAGE", "new", true);
807920 fail("Expected IllegalAccessException");
808 } catch (IllegalAccessException e) {
921 } catch (final IllegalAccessException e) {
809922 // pass
810923 }
811924 try {
812925 FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PRIVATE", "new", true);
813926 fail("Expected IllegalAccessException");
814 } catch (IllegalAccessException e) {
927 } catch (final IllegalAccessException e) {
815928 // pass
816929 }
817930 }
823936 try {
824937 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutableProtected", "new");
825938 fail("Expected IllegalArgumentException");
826 } catch (IllegalArgumentException e) {
939 } catch (final IllegalArgumentException e) {
827940 // pass
828941 }
829942 try {
830943 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePackage", "new");
831944 fail("Expected IllegalArgumentException");
832 } catch (IllegalArgumentException e) {
945 } catch (final IllegalArgumentException e) {
833946 // pass
834947 }
835948 try {
836949 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePrivate", "new");
837950 fail("Expected IllegalArgumentException");
838 } catch (IllegalArgumentException e) {
951 } catch (final IllegalArgumentException e) {
839952 // pass
840953 }
841954 try {
842955 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PUBLIC", "new");
843956 fail("Expected IllegalAccessException");
844 } catch (IllegalAccessException e) {
957 } catch (final IllegalAccessException e) {
845958 // pass
846959 }
847960 try {
848961 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PROTECTED", "new");
849962 fail("Expected IllegalArgumentException");
850 } catch (IllegalArgumentException e) {
963 } catch (final IllegalArgumentException e) {
851964 // pass
852965 }
853966 try {
854967 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PACKAGE", "new");
855968 fail("Expected IllegalArgumentException");
856 } catch (IllegalArgumentException e) {
969 } catch (final IllegalArgumentException e) {
857970 // pass
858971 }
859972 try {
860973 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PRIVATE", "new");
861974 fail("Expected IllegalArgumentException");
862 } catch (IllegalArgumentException e) {
975 } catch (final IllegalArgumentException e) {
863976 // pass
864977 }
865978 }
877990 try {
878991 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PUBLIC", "new", true);
879992 fail("Expected IllegalAccessException");
880 } catch (IllegalAccessException e) {
993 } catch (final IllegalAccessException e) {
881994 // pass
882995 }
883996 try {
884997 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PROTECTED", "new", true);
885998 fail("Expected IllegalAccessException");
886 } catch (IllegalAccessException e) {
999 } catch (final IllegalAccessException e) {
8871000 // pass
8881001 }
8891002 try {
8901003 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PACKAGE", "new", true);
8911004 fail("Expected IllegalAccessException");
892 } catch (IllegalAccessException e) {
1005 } catch (final IllegalAccessException e) {
8931006 // pass
8941007 }
8951008 try {
8961009 FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PRIVATE", "new", true);
8971010 fail("Expected IllegalAccessException");
898 } catch (IllegalAccessException e) {
1011 } catch (final IllegalAccessException e) {
8991012 // pass
9001013 }
9011014 }
9091022 try {
9101023 FieldUtils.writeField(field, publicChild, Boolean.TRUE);
9111024 fail("Expected IllegalAccessException");
912 } catch (IllegalAccessException e) {
1025 } catch (final IllegalAccessException e) {
9131026 // pass
9141027 }
9151028 field = parentClass.getDeclaredField("i");
9161029 try {
9171030 FieldUtils.writeField(field, publicChild, Integer.valueOf(Integer.MAX_VALUE));
918 } catch (IllegalAccessException e) {
1031 } catch (final IllegalAccessException e) {
9191032 // pass
9201033 }
9211034 field = parentClass.getDeclaredField("d");
9221035 try {
9231036 FieldUtils.writeField(field, publicChild, Double.valueOf(Double.MAX_VALUE));
924 } catch (IllegalAccessException e) {
1037 } catch (final IllegalAccessException e) {
9251038 // pass
9261039 }
9271040 }
9491062 try {
9501063 FieldUtils.writeField(publicChild, "b", Boolean.TRUE);
9511064 fail("Expected IllegalArgumentException");
952 } catch (IllegalArgumentException e) {
1065 } catch (final IllegalArgumentException e) {
9531066 // pass
9541067 }
9551068 try {
9561069 FieldUtils.writeField(publicChild, "i", Integer.valueOf(1));
9571070 fail("Expected IllegalArgumentException");
958 } catch (IllegalArgumentException e) {
1071 } catch (final IllegalArgumentException e) {
9591072 // pass
9601073 }
9611074 try {
9621075 FieldUtils.writeField(publicChild, "d", Double.valueOf(1.0));
9631076 fail("Expected IllegalArgumentException");
964 } catch (IllegalArgumentException e) {
1077 } catch (final IllegalArgumentException e) {
9651078 // pass
9661079 }
9671080
9791092 try {
9801093 FieldUtils.writeField(privatelyShadowedChild, "b", Boolean.TRUE);
9811094 fail("Expected IllegalArgumentException");
982 } catch (IllegalArgumentException e) {
1095 } catch (final IllegalArgumentException e) {
9831096 // pass
9841097 }
9851098 try {
9861099 FieldUtils.writeField(privatelyShadowedChild, "i", Integer.valueOf(1));
9871100 fail("Expected IllegalArgumentException");
988 } catch (IllegalArgumentException e) {
1101 } catch (final IllegalArgumentException e) {
9891102 // pass
9901103 }
9911104 try {
9921105 FieldUtils.writeField(privatelyShadowedChild, "d", Double.valueOf(1.0));
9931106 fail("Expected IllegalArgumentException");
994 } catch (IllegalArgumentException e) {
1107 } catch (final IllegalArgumentException e) {
9951108 // pass
9961109 }
9971110 }
10311144 try {
10321145 FieldUtils.writeDeclaredField(publicChild, "s", "S");
10331146 fail("Expected IllegalArgumentException");
1034 } catch (IllegalArgumentException e) {
1147 } catch (final IllegalArgumentException e) {
10351148 // pass
10361149 }
10371150 try {
10381151 FieldUtils.writeDeclaredField(publicChild, "b", Boolean.TRUE);
10391152 fail("Expected IllegalArgumentException");
1040 } catch (IllegalArgumentException e) {
1153 } catch (final IllegalArgumentException e) {
10411154 // pass
10421155 }
10431156 try {
10441157 FieldUtils.writeDeclaredField(publicChild, "i", Integer.valueOf(1));
10451158 fail("Expected IllegalArgumentException");
1046 } catch (IllegalArgumentException e) {
1159 } catch (final IllegalArgumentException e) {
10471160 // pass
10481161 }
10491162 try {
10501163 FieldUtils.writeDeclaredField(publicChild, "d", Double.valueOf(1.0));
10511164 fail("Expected IllegalArgumentException");
1052 } catch (IllegalArgumentException e) {
1165 } catch (final IllegalArgumentException e) {
10531166 // pass
10541167 }
10551168
10651178 try {
10661179 FieldUtils.writeDeclaredField(privatelyShadowedChild, "s", "S");
10671180 fail("Expected IllegalArgumentException");
1068 } catch (IllegalArgumentException e) {
1181 } catch (final IllegalArgumentException e) {
10691182 // pass
10701183 }
10711184 try {
10721185 FieldUtils.writeDeclaredField(privatelyShadowedChild, "b", Boolean.TRUE);
10731186 fail("Expected IllegalArgumentException");
1074 } catch (IllegalArgumentException e) {
1187 } catch (final IllegalArgumentException e) {
10751188 // pass
10761189 }
10771190 try {
10781191 FieldUtils.writeDeclaredField(privatelyShadowedChild, "i", Integer.valueOf(1));
10791192 fail("Expected IllegalArgumentException");
1080 } catch (IllegalArgumentException e) {
1193 } catch (final IllegalArgumentException e) {
10811194 // pass
10821195 }
10831196 try {
10841197 FieldUtils.writeDeclaredField(privatelyShadowedChild, "d", Double.valueOf(1.0));
10851198 fail("Expected IllegalArgumentException");
1086 } catch (IllegalArgumentException e) {
1199 } catch (final IllegalArgumentException e) {
10871200 // pass
10881201 }
10891202 }
10931206 try {
10941207 FieldUtils.writeDeclaredField(publicChild, "s", "S", true);
10951208 fail("Expected IllegalArgumentException");
1096 } catch (IllegalArgumentException e) {
1209 } catch (final IllegalArgumentException e) {
10971210 // pass
10981211 }
10991212 try {
11001213 FieldUtils.writeDeclaredField(publicChild, "b", Boolean.TRUE, true);
11011214 fail("Expected IllegalArgumentException");
1102 } catch (IllegalArgumentException e) {
1215 } catch (final IllegalArgumentException e) {
11031216 // pass
11041217 }
11051218 try {
11061219 FieldUtils.writeDeclaredField(publicChild, "i", Integer.valueOf(1), true);
11071220 fail("Expected IllegalArgumentException");
1108 } catch (IllegalArgumentException e) {
1221 } catch (final IllegalArgumentException e) {
11091222 // pass
11101223 }
11111224 try {
11121225 FieldUtils.writeDeclaredField(publicChild, "d", Double.valueOf(1.0), true);
11131226 fail("Expected IllegalArgumentException");
1114 } catch (IllegalArgumentException e) {
1227 } catch (final IllegalArgumentException e) {
11151228 // pass
11161229 }
11171230
11341247 assertEquals(Double.valueOf(0.0), FieldUtils.readDeclaredField(privatelyShadowedChild, "d", true));
11351248 }
11361249
1137 @Test(expected=IllegalArgumentException.class)
1250 @Test(expected = IllegalArgumentException.class)
11381251 public void testAmbig() {
11391252 FieldUtils.getField(Ambig.class, "VALUE");
11401253 }
11411254
1255 @Test
1256 public void testRemoveFinalModifier() throws Exception {
1257 Field field = StaticContainer.class.getDeclaredField("IMMUTABLE_PRIVATE_2");
1258 assertTrue(Modifier.isFinal(field.getModifiers()));
1259 FieldUtils.removeFinalModifier(field);
1260 assertFalse(Modifier.isFinal(field.getModifiers()));
1261 }
11421262 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect;
17
18 import org.apache.commons.lang3.reflect.testbed.AnotherChild;
19 import org.apache.commons.lang3.reflect.testbed.AnotherParent;
20 import org.apache.commons.lang3.reflect.testbed.Grandchild;
21 import org.junit.Test;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25
26 /**
27 * Unit tests InheritanceUtils
28 */
29 public class InheritanceUtilsTest {
30
31 @Test
32 public void testConstructor() throws Exception {
33 assertNotNull(InheritanceUtils.class.newInstance());
34 }
35
36 @Test
37 public void testDistanceGreaterThanZero() {
38 assertEquals(1, InheritanceUtils.distance(AnotherChild.class, AnotherParent.class));
39 assertEquals(1, InheritanceUtils.distance(Grandchild.class, AnotherChild.class));
40 assertEquals(2, InheritanceUtils.distance(Grandchild.class, AnotherParent.class));
41 assertEquals(3, InheritanceUtils.distance(Grandchild.class, Object.class));
42 }
43
44 @Test
45 public void testDistanceEqual() {
46 assertEquals(0, InheritanceUtils.distance(AnotherChild.class, AnotherChild.class));
47 }
48
49 @Test
50 public void testDistanceEqualObject() {
51 assertEquals(0, InheritanceUtils.distance(Object.class, Object.class));
52 }
53
54 @Test
55 public void testDistanceNullChild() {
56 assertEquals(-1, InheritanceUtils.distance(null, Object.class));
57 }
58
59 @Test
60 public void testDistanceNullParent() {
61 assertEquals(-1, InheritanceUtils.distance(Object.class, null));
62 }
63
64 @Test
65 public void testDistanceNullParentNullChild() {
66 assertEquals(-1, InheritanceUtils.distance(null, null));
67 }
68
69 @Test
70 public void testDistanceDisjoint() {
71 assertEquals(-1, InheritanceUtils.distance(Boolean.class, String.class));
72 }
73
74 @Test
75 public void testDistanceReverseParentChild() {
76 assertEquals(-1, InheritanceUtils.distance(Object.class, Grandchild.class));
77 }
78 }
1616 package org.apache.commons.lang3.reflect;
1717
1818 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
1920 import static org.junit.Assert.assertNotNull;
2021 import static org.junit.Assert.assertNotSame;
2122 import static org.junit.Assert.assertNull;
2425 import static org.junit.Assert.fail;
2526
2627 import java.lang.reflect.Method;
28 import java.lang.reflect.Type;
2729 import java.util.Arrays;
2830 import java.util.HashMap;
31 import java.util.Iterator;
2932 import java.util.Map;
3033
3134 import org.apache.commons.lang3.ArrayUtils;
3235 import org.apache.commons.lang3.math.NumberUtils;
3336 import org.apache.commons.lang3.mutable.Mutable;
3437 import org.apache.commons.lang3.mutable.MutableObject;
38 import org.apache.commons.lang3.ClassUtils.Interfaces;
39 import org.apache.commons.lang3.reflect.testbed.GenericConsumer;
40 import org.apache.commons.lang3.reflect.testbed.GenericParent;
41 import org.apache.commons.lang3.reflect.testbed.StringParameterizedChild;
3542 import org.junit.Before;
3643 import org.junit.Test;
3744
3845 /**
3946 * Unit tests MethodUtils
40 * @version $Id: MethodUtilsTest.java 1166253 2011-09-07 16:27:42Z ggregory $
47 * @version $Id: MethodUtilsTest.java 1510301 2013-08-04 18:40:48Z mbenson $
4148 */
4249 public class MethodUtilsTest {
4350
5562 return "bar()";
5663 }
5764
58 public static String bar(int i) {
65 public static String bar(final int i) {
5966 return "bar(int)";
6067 }
6168
62 public static String bar(Integer i) {
69 public static String bar(final Integer i) {
6370 return "bar(Integer)";
6471 }
6572
66 public static String bar(double d) {
73 public static String bar(final double d) {
6774 return "bar(double)";
6875 }
6976
70 public static String bar(String s) {
77 public static String bar(final String s) {
7178 return "bar(String)";
7279 }
7380
74 public static String bar(Object o) {
81 public static String bar(final Object o) {
7582 return "bar(Object)";
7683 }
7784
78 public static void oneParameterStatic(String s) {
85 public static void oneParameterStatic(final String s) {
7986 // empty
8087 }
8188
8895 return "foo()";
8996 }
9097
91 public String foo(int i) {
98 public String foo(final int i) {
9299 return "foo(int)";
93100 }
94101
95 public String foo(Integer i) {
102 public String foo(final Integer i) {
96103 return "foo(Integer)";
97104 }
98105
99 public String foo(double d) {
106 public String foo(final double d) {
100107 return "foo(double)";
101108 }
102109
103 public String foo(String s) {
110 public String foo(final String s) {
104111 return "foo(String)";
105112 }
106113
107 public String foo(Object o) {
114 public String foo(final Object o) {
108115 return "foo(Object)";
109116 }
110117
111 public void oneParameter(String s) {
118 public void oneParameter(final String s) {
112119 // empty
113120 }
114121 }
115122
116123 private static class TestMutable implements Mutable<Object> {
124 @Override
117125 public Object getValue() {
118126 return null;
119127 }
120128
121 public void setValue(Object value) {
129 @Override
130 public void setValue(final Object value) {
122131 }
123132 }
124133
125134 private TestBean testBean;
126 private Map<Class<?>, Class<?>[]> classCache = new HashMap<Class<?>, Class<?>[]>();
135 private final Map<Class<?>, Class<?>[]> classCache = new HashMap<Class<?>, Class<?>[]>();
127136
128137 @Before
129138 public void setUp() throws Exception {
182191 MethodUtils
183192 .invokeExactMethod(testBean, "foo", NumberUtils.BYTE_ONE);
184193 fail("should throw NoSuchMethodException");
185 } catch (NoSuchMethodException e) {
194 } catch (final NoSuchMethodException e) {
186195 }
187196 try {
188197 MethodUtils
189198 .invokeExactMethod(testBean, "foo", NumberUtils.LONG_ONE);
190199 fail("should throw NoSuchMethodException");
191 } catch (NoSuchMethodException e) {
200 } catch (final NoSuchMethodException e) {
192201 }
193202 try {
194203 MethodUtils.invokeExactMethod(testBean, "foo", Boolean.TRUE);
195204 fail("should throw NoSuchMethodException");
196 } catch (NoSuchMethodException e) {
205 } catch (final NoSuchMethodException e) {
197206 }
198207 }
199208
223232 try {
224233 MethodUtils.invokeStaticMethod(TestBean.class, "does_not_exist");
225234 fail("should throw NoSuchMethodException");
226 } catch (NoSuchMethodException e) {
235 } catch (final NoSuchMethodException e) {
227236 }
228237 }
229238
249258 MethodUtils.invokeExactStaticMethod(TestBean.class, "bar",
250259 NumberUtils.BYTE_ONE);
251260 fail("should throw NoSuchMethodException");
252 } catch (NoSuchMethodException e) {
261 } catch (final NoSuchMethodException e) {
253262 }
254263 try {
255264 MethodUtils.invokeExactStaticMethod(TestBean.class, "bar",
256265 NumberUtils.LONG_ONE);
257266 fail("should throw NoSuchMethodException");
258 } catch (NoSuchMethodException e) {
267 } catch (final NoSuchMethodException e) {
259268 }
260269 try {
261270 MethodUtils.invokeExactStaticMethod(TestBean.class, "bar",
262271 Boolean.TRUE);
263272 fail("should throw NoSuchMethodException");
264 } catch (NoSuchMethodException e) {
273 } catch (final NoSuchMethodException e) {
265274 }
266275 }
267276
268277 @Test
269278 public void testGetAccessibleInterfaceMethod() throws Exception {
270 Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null };
271 for (Class<?>[] element : p) {
272 Method method = TestMutable.class.getMethod("getValue", element);
273 Method accessibleMethod = MethodUtils.getAccessibleMethod(method);
279 final Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null };
280 for (final Class<?>[] element : p) {
281 final Method method = TestMutable.class.getMethod("getValue", element);
282 final Method accessibleMethod = MethodUtils.getAccessibleMethod(method);
274283 assertNotSame(accessibleMethod, method);
275284 assertSame(Mutable.class, accessibleMethod.getDeclaringClass());
276285 }
278287
279288 @Test
280289 public void testGetAccessibleMethodPrivateInterface() throws Exception {
281 Method expected = TestBeanWithInterfaces.class.getMethod("foo");
290 final Method expected = TestBeanWithInterfaces.class.getMethod("foo");
282291 assertNotNull(expected);
283 Method actual = MethodUtils.getAccessibleMethod(TestBeanWithInterfaces.class, "foo");
292 final Method actual = MethodUtils.getAccessibleMethod(TestBeanWithInterfaces.class, "foo");
284293 assertNull(actual);
285294 }
286295
287296 @Test
288297 public void testGetAccessibleInterfaceMethodFromDescription()
289298 throws Exception {
290 Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null };
291 for (Class<?>[] element : p) {
292 Method accessibleMethod = MethodUtils.getAccessibleMethod(
299 final Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null };
300 for (final Class<?>[] element : p) {
301 final Method accessibleMethod = MethodUtils.getAccessibleMethod(
293302 TestMutable.class, "getValue", element);
294303 assertSame(Mutable.class, accessibleMethod.getDeclaringClass());
295304 }
311320
312321 @Test
313322 public void testGetAccessibleMethodInaccessible() throws Exception {
314 Method expected = TestBean.class.getDeclaredMethod("privateStuff");
315 Method actual = MethodUtils.getAccessibleMethod(expected);
323 final Method expected = TestBean.class.getDeclaredMethod("privateStuff");
324 final Method actual = MethodUtils.getAccessibleMethod(expected);
316325 assertNull(actual);
317326 }
318327
368377 singletonArray(ChildObject.class), singletonArray(ChildInterface.class));
369378 }
370379
371 private void expectMatchingAccessibleMethodParameterTypes(Class<?> cls,
372 String methodName, Class<?>[] requestTypes, Class<?>[] actualTypes) {
373 Method m = MethodUtils.getMatchingAccessibleMethod(cls, methodName,
380 @Test
381 public void testNullArgument() {
382 expectMatchingAccessibleMethodParameterTypes(TestBean.class, "oneParameter",
383 singletonArray(null), singletonArray(String.class));
384 }
385
386 @Test
387 public void testGetOverrideHierarchyIncludingInterfaces() {
388 final Method method = MethodUtils.getAccessibleMethod(StringParameterizedChild.class, "consume", String.class);
389 final Iterator<MethodDescriptor> expected =
390 Arrays.asList(new MethodDescriptor(StringParameterizedChild.class, "consume", String.class),
391 new MethodDescriptor(GenericParent.class, "consume", GenericParent.class.getTypeParameters()[0]),
392 new MethodDescriptor(GenericConsumer.class, "consume", GenericConsumer.class.getTypeParameters()[0]))
393 .iterator();
394 for (Method m : MethodUtils.getOverrideHierarchy(method, Interfaces.INCLUDE)) {
395 assertTrue(expected.hasNext());
396 final MethodDescriptor md = expected.next();
397 assertEquals(md.declaringClass, m.getDeclaringClass());
398 assertEquals(md.name, m.getName());
399 assertEquals(md.parameterTypes.length, m.getParameterTypes().length);
400 for (int i = 0; i < md.parameterTypes.length; i++) {
401 assertTrue(TypeUtils.equals(md.parameterTypes[i], m.getGenericParameterTypes()[i]));
402 }
403 }
404 assertFalse(expected.hasNext());
405 }
406
407 @Test
408 public void testGetOverrideHierarchyExcludingInterfaces() {
409 final Method method = MethodUtils.getAccessibleMethod(StringParameterizedChild.class, "consume", String.class);
410 final Iterator<MethodDescriptor> expected =
411 Arrays.asList(new MethodDescriptor(StringParameterizedChild.class, "consume", String.class),
412 new MethodDescriptor(GenericParent.class, "consume", GenericParent.class.getTypeParameters()[0]))
413 .iterator();
414 for (Method m : MethodUtils.getOverrideHierarchy(method, Interfaces.EXCLUDE)) {
415 assertTrue(expected.hasNext());
416 final MethodDescriptor md = expected.next();
417 assertEquals(md.declaringClass, m.getDeclaringClass());
418 assertEquals(md.name, m.getName());
419 assertEquals(md.parameterTypes.length, m.getParameterTypes().length);
420 for (int i = 0; i < md.parameterTypes.length; i++) {
421 assertTrue(TypeUtils.equals(md.parameterTypes[i], m.getGenericParameterTypes()[i]));
422 }
423 }
424 assertFalse(expected.hasNext());
425 }
426
427 private void expectMatchingAccessibleMethodParameterTypes(final Class<?> cls,
428 final String methodName, final Class<?>[] requestTypes, final Class<?>[] actualTypes) {
429 final Method m = MethodUtils.getMatchingAccessibleMethod(cls, methodName,
374430 requestTypes);
375431 assertTrue(toString(m.getParameterTypes()) + " not equals "
376432 + toString(actualTypes), Arrays.equals(actualTypes, m
377433 .getParameterTypes()));
378434 }
379435
380 private String toString(Class<?>[] c) {
436 private String toString(final Class<?>[] c) {
381437 return Arrays.asList(c).toString();
382438 }
383439
384 private Class<?>[] singletonArray(Class<?> c) {
440 private Class<?>[] singletonArray(final Class<?> c) {
385441 Class<?>[] result = classCache.get(c);
386442 if (result == null) {
387443 result = new Class[] { c };
391447 }
392448
393449 public static class InheritanceBean {
394 public void testOne(Object obj) {}
395 public void testOne(GrandParentObject obj) {}
396 public void testOne(ParentObject obj) {}
397 public void testTwo(Object obj) {}
398 public void testTwo(GrandParentObject obj) {}
399 public void testTwo(ChildInterface obj) {}
450 public void testOne(final Object obj) {}
451 public void testOne(final GrandParentObject obj) {}
452 public void testOne(final ParentObject obj) {}
453 public void testTwo(final Object obj) {}
454 public void testTwo(final GrandParentObject obj) {}
455 public void testTwo(final ChildInterface obj) {}
400456 }
401457
402458 interface ChildInterface {}
403459 public static class GrandParentObject {}
404460 public static class ParentObject extends GrandParentObject {}
405461 public static class ChildObject extends ParentObject implements ChildInterface {}
406
462
463 private static class MethodDescriptor {
464 final Class<?> declaringClass;
465 final String name;
466 final Type[] parameterTypes;
467
468 MethodDescriptor(Class<?> declaringClass, String name, Type... parameterTypes) {
469 this.declaringClass = declaringClass;
470 this.name = name;
471 this.parameterTypes = parameterTypes;
472 }
473 }
407474 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect;
17
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertNotEquals;
20 import static org.junit.Assert.assertTrue;
21
22 import java.util.List;
23
24 import org.junit.Test;
25
26 public class TypeLiteralTest {
27
28 @Test
29 public void testBasic() {
30 assertTrue(TypeUtils.equals(String.class, new TypeLiteral<String>() {}.value));
31 assertTrue(TypeUtils.equals(TypeUtils.parameterize(List.class, String.class),
32 new TypeLiteral<List<String>>() {}.value));
33 }
34
35 @Test
36 public void testTyped() {
37 final Typed<String> stringType = new TypeLiteral<String>() {};
38 assertTrue(TypeUtils.equals(String.class, stringType.getType()));
39 final Typed<List<String>> listOfStringType = new TypeLiteral<List<String>>() {};
40 assertTrue(TypeUtils.equals(TypeUtils.parameterize(List.class, String.class), listOfStringType.getType()));
41 }
42
43 @Test
44 public void testEquals() {
45 assertEquals(new TypeLiteral<String>() {}, new TypeLiteral<String>() {});
46 assertEquals(new TypeLiteral<List<String>>() {}, new TypeLiteral<List<String>>() {});
47 assertNotEquals(new TypeLiteral<String>() {}, new TypeLiteral<List<String>>() {});
48 }
49
50 @SuppressWarnings("rawtypes")
51 @Test(expected = NullPointerException.class)
52 public void testRaw() {
53 new TypeLiteral() {};
54 }
55 }
1616 package org.apache.commons.lang3.reflect;
1717
1818 import java.io.Serializable;
19 import java.lang.reflect.Field;
20 import java.lang.reflect.GenericArrayType;
1921 import java.lang.reflect.Method;
2022 import java.lang.reflect.ParameterizedType;
2123 import java.lang.reflect.Type;
2224 import java.lang.reflect.TypeVariable;
25 import java.lang.reflect.WildcardType;
2326 import java.net.URI;
2427 import java.util.Arrays;
2528 import java.util.Collection;
3841
3942 /**
4043 * Test TypeUtils
41 * @version $Id: TypeUtilsTest.java 1153484 2011-08-03 13:39:42Z ggregory $
44 * @version $Id: TypeUtilsTest.java 1553929 2013-12-28 21:19:39Z ggregory $
4245 */
43 @SuppressWarnings({ "unchecked", "unused" , "rawtypes", "null"})
46 @SuppressWarnings({ "unchecked", "unused" , "rawtypes" })
4447 //raw types, where used, are used purposely
4548 public class TypeUtilsTest<B> {
4649
9598
9699 public static URI uri;
97100
98 public void dummyMethod(List list0, List<Object> list1, List<?> list2,
99 List<? super Object> list3, List<String> list4, List<? extends String> list5,
100 List<? super String> list6, List[] list7, List<Object>[] list8, List<?>[] list9,
101 List<? super Object>[] list10, List<String>[] list11, List<? extends String>[] list12,
102 List<? super String>[] list13) {
101 public void dummyMethod(final List list0, final List<Object> list1, final List<?> list2,
102 final List<? super Object> list3, final List<String> list4, final List<? extends String> list5,
103 final List<? super String> list6, final List[] list7, final List<Object>[] list8, final List<?>[] list9,
104 final List<? super Object>[] list10, final List<String>[] list11, final List<? extends String>[] list12,
105 final List<? super String>[] list13) {
103106 }
104107
105108 @SuppressWarnings("boxing") // deliberately used here
120123 List<String>[] list11 = null;
121124 List<? extends String>[] list12 = null;
122125 List<? super String>[] list13;
123 Class<?> clazz = getClass();
124 Method method = clazz.getMethod("dummyMethod", List.class, List.class, List.class,
126 final Class<?> clazz = getClass();
127 final Method method = clazz.getMethod("dummyMethod", List.class, List.class, List.class,
125128 List.class, List.class, List.class, List.class, List[].class, List[].class,
126129 List[].class, List[].class, List[].class, List[].class, List[].class);
127 Type[] types = method.getGenericParameterTypes();
130 final Type[] types = method.getGenericParameterTypes();
128131 // list0 = list0;
129132 delegateBooleanAssertion(types, 0, 0, true);
130133 list1 = list0;
322325 delegateBooleanAssertion(types, 13, 12, false);
323326 // list13 = list13;
324327 delegateBooleanAssertion(types, 13, 13, true);
325 Type disType = getClass().getField("dis").getGenericType();
328 final Type disType = getClass().getField("dis").getGenericType();
326329 // Reporter.log( ( ( ParameterizedType ) disType
327330 // ).getOwnerType().getClass().toString() );
328 Type datType = getClass().getField("dat").getGenericType();
329 Type daType = getClass().getField("da").getGenericType();
330 Type uhderType = getClass().getField("uhder").getGenericType();
331 Type dingType = getClass().getField("ding").getGenericType();
332 Type testerType = getClass().getField("tester").getGenericType();
333 Type tester2Type = getClass().getField("tester2").getGenericType();
334 Type dat2Type = getClass().getField("dat2").getGenericType();
335 Type dat3Type = getClass().getField("dat3").getGenericType();
331 final Type datType = getClass().getField("dat").getGenericType();
332 final Type daType = getClass().getField("da").getGenericType();
333 final Type uhderType = getClass().getField("uhder").getGenericType();
334 final Type dingType = getClass().getField("ding").getGenericType();
335 final Type testerType = getClass().getField("tester").getGenericType();
336 final Type tester2Type = getClass().getField("tester2").getGenericType();
337 final Type dat2Type = getClass().getField("dat2").getGenericType();
338 final Type dat3Type = getClass().getField("dat3").getGenericType();
336339 dis = dat;
337340 Assert.assertTrue(TypeUtils.isAssignable(datType, disType));
338341 // dis = da;
340343 dis = uhder;
341344 Assert.assertTrue(TypeUtils.isAssignable(uhderType, disType));
342345 dis = ding;
343 Assert.assertTrue("WRONG!", TypeUtils.isAssignable(dingType, disType));
346 Assert.assertFalse(String.format("type %s not assignable to %s!", dingType, disType),
347 TypeUtils.isAssignable(dingType, disType));
344348 dis = tester;
345349 Assert.assertTrue(TypeUtils.isAssignable(testerType, disType));
346350 // dis = tester2;
351355 Assert.assertFalse(TypeUtils.isAssignable(datType, dat2Type));
352356 // dat = dat3;
353357 Assert.assertFalse(TypeUtils.isAssignable(dat3Type, datType));
354 char ch = 0;
355 boolean bo = false;
356 byte by = 0;
357 short sh = 0;
358 final char ch = 0;
359 final boolean bo = false;
360 final byte by = 0;
361 final short sh = 0;
358362 int in = 0;
359363 long lo = 0;
360 float fl = 0;
364 final float fl = 0;
361365 double du = 0;
362366 du = ch;
363367 Assert.assertTrue(TypeUtils.isAssignable(char.class, double.class));
381385 Assert.assertFalse(TypeUtils.isAssignable(Integer.class, Long.class));
382386 in = Integer.valueOf(0);
383387 Assert.assertTrue(TypeUtils.isAssignable(Integer.class, int.class));
384 Integer inte = in;
388 final Integer inte = in;
385389 Assert.assertTrue(TypeUtils.isAssignable(int.class, Integer.class));
386390 Assert.assertTrue(TypeUtils.isAssignable(int.class, Number.class));
387391 Assert.assertTrue(TypeUtils.isAssignable(int.class, Object.class));
388 Type intComparableType = getClass().getField("intComparable").getGenericType();
392 final Type intComparableType = getClass().getField("intComparable").getGenericType();
389393 intComparable = 1;
390394 Assert.assertTrue(TypeUtils.isAssignable(int.class, intComparableType));
391395 Assert.assertTrue(TypeUtils.isAssignable(int.class, Comparable.class));
392 Serializable ser = 1;
396 final Serializable ser = 1;
393397 Assert.assertTrue(TypeUtils.isAssignable(int.class, Serializable.class));
394 Type longComparableType = getClass().getField("longComparable").getGenericType();
398 final Type longComparableType = getClass().getField("longComparable").getGenericType();
395399 // longComparable = 1;
396400 Assert.assertFalse(TypeUtils.isAssignable(int.class, longComparableType));
397401 // longComparable = Integer.valueOf( 0 );
399403 // int[] ia;
400404 // long[] la = ia;
401405 Assert.assertFalse(TypeUtils.isAssignable(int[].class, long[].class));
402 Integer[] ia = null;
403 Type caType = getClass().getField("intWildcardComparable").getGenericType();
406 final Integer[] ia = null;
407 final Type caType = getClass().getField("intWildcardComparable").getGenericType();
404408 intWildcardComparable = ia;
405409 Assert.assertTrue(TypeUtils.isAssignable(Integer[].class, caType));
406410 // int[] ina = ia;
407411 Assert.assertFalse(TypeUtils.isAssignable(Integer[].class, int[].class));
408 int[] ina = null;
412 final int[] ina = null;
409413 Object[] oa;
410414 // oa = ina;
411415 Assert.assertFalse(TypeUtils.isAssignable(int[].class, Object[].class));
412416 oa = new Integer[0];
413417 Assert.assertTrue(TypeUtils.isAssignable(Integer[].class, Object[].class));
414 Type bClassType = AClass.class.getField("bClass").getGenericType();
415 Type cClassType = AClass.class.getField("cClass").getGenericType();
416 Type dClassType = AClass.class.getField("dClass").getGenericType();
417 Type eClassType = AClass.class.getField("eClass").getGenericType();
418 Type fClassType = AClass.class.getField("fClass").getGenericType();
419 AClass aClass = new AClass(new AAClass<String>());
418 final Type bClassType = AClass.class.getField("bClass").getGenericType();
419 final Type cClassType = AClass.class.getField("cClass").getGenericType();
420 final Type dClassType = AClass.class.getField("dClass").getGenericType();
421 final Type eClassType = AClass.class.getField("eClass").getGenericType();
422 final Type fClassType = AClass.class.getField("fClass").getGenericType();
423 final AClass aClass = new AClass(new AAClass<String>());
420424 aClass.bClass = aClass.cClass;
421425 Assert.assertTrue(TypeUtils.isAssignable(cClassType, bClassType));
422426 aClass.bClass = aClass.dClass;
439443 Assert.assertTrue(TypeUtils.isAssignable(fClassType, eClassType));
440444 }
441445
442 public void delegateBooleanAssertion(Type[] types, int i2, int i1, boolean expected) {
443 Type type1 = types[i1];
444 Type type2 = types[i2];
445 boolean isAssignable = TypeUtils.isAssignable(type2, type1);
446 public void delegateBooleanAssertion(final Type[] types, final int i2, final int i1, final boolean expected) {
447 final Type type1 = types[i1];
448 final Type type2 = types[i2];
449 final boolean isAssignable = TypeUtils.isAssignable(type2, type1);
446450
447451 if (expected) {
448452 Assert.assertTrue("[" + i1 + ", " + i2 + "]: From "
458462 @SuppressWarnings("boxing") // boxing is deliberate here
459463 @Test
460464 public void testIsInstance() throws SecurityException, NoSuchFieldException {
461 Type intComparableType = getClass().getField("intComparable").getGenericType();
462 Type uriComparableType = getClass().getField("uriComparable").getGenericType();
465 final Type intComparableType = getClass().getField("intComparable").getGenericType();
466 final Type uriComparableType = getClass().getField("uriComparable").getGenericType();
463467 intComparable = 1;
464468 Assert.assertTrue(TypeUtils.isInstance(1, intComparableType));
465469 // uriComparable = 1;
488492 Assert.assertEquals("Type argument of Comparable from int: " + typeArg, Integer.class,
489493 typeVarAssigns.get(treeSetTypeVar));
490494
491 Collection<Integer> col = Arrays.asList(new Integer[0]);
495 final Collection<Integer> col = Arrays.asList(new Integer[0]);
492496 typeVarAssigns = TypeUtils.getTypeArguments(List.class, Collection.class);
493497 treeSetTypeVar = Comparable.class.getTypeParameters()[0];
494498 Assert.assertFalse("Type var assigns for Collection from List: " + typeVarAssigns,
498502 Assert.assertTrue(typeVarAssigns.size() == 2);
499503 Assert.assertEquals(String.class, typeVarAssigns.get(AAClass.class.getTypeParameters()[0]));
500504 Assert.assertEquals(String.class, typeVarAssigns.get(AAClass.BBClass.class.getTypeParameters()[0]));
505
506 typeVarAssigns = TypeUtils.getTypeArguments(Other.class, This.class);
507 Assert.assertEquals(2, typeVarAssigns.size());
508 Assert.assertEquals(String.class, typeVarAssigns.get(This.class.getTypeParameters()[0]));
509 Assert.assertEquals(Other.class.getTypeParameters()[0], typeVarAssigns.get(This.class.getTypeParameters()[1]));
510
511 typeVarAssigns = TypeUtils.getTypeArguments(And.class, This.class);
512 Assert.assertEquals(2, typeVarAssigns.size());
513 Assert.assertEquals(Number.class, typeVarAssigns.get(This.class.getTypeParameters()[0]));
514 Assert.assertEquals(Number.class, typeVarAssigns.get(This.class.getTypeParameters()[1]));
515
516 typeVarAssigns = TypeUtils.getTypeArguments(Thing.class, Other.class);
517 Assert.assertEquals(2, typeVarAssigns.size());
518 Assert.assertEquals(getClass().getTypeParameters()[0], typeVarAssigns.get(getClass().getTypeParameters()[0]));
519 Assert.assertEquals(getClass().getTypeParameters()[0], typeVarAssigns.get(Other.class.getTypeParameters()[0]));
501520 }
502521
503522 @Test
504523 public void testTypesSatisfyVariables() throws SecurityException, NoSuchFieldException,
505524 NoSuchMethodException {
506 Map<TypeVariable<?>, Type> typeVarAssigns = new HashMap<TypeVariable<?>, Type>();
507 Integer max = TypeUtilsTest.stub();
525 final Map<TypeVariable<?>, Type> typeVarAssigns = new HashMap<TypeVariable<?>, Type>();
526 final Integer max = TypeUtilsTest.<Integer> stub();
508527 typeVarAssigns.put(getClass().getMethod("stub").getTypeParameters()[0], Integer.class);
509528 Assert.assertTrue(TypeUtils.typesSatisfyVariables(typeVarAssigns));
510529 typeVarAssigns.clear();
518537 @Test
519538 public void testDetermineTypeVariableAssignments() throws SecurityException,
520539 NoSuchFieldException, NoSuchMethodException {
521 ParameterizedType iterableType = (ParameterizedType) getClass().getField("iterable")
540 final ParameterizedType iterableType = (ParameterizedType) getClass().getField("iterable")
522541 .getGenericType();
523 Map<TypeVariable<?>, Type> typeVarAssigns = TypeUtils.determineTypeArguments(TreeSet.class,
542 final Map<TypeVariable<?>, Type> typeVarAssigns = TypeUtils.determineTypeArguments(TreeSet.class,
524543 iterableType);
525 TypeVariable<?> treeSetTypeVar = TreeSet.class.getTypeParameters()[0];
544 final TypeVariable<?> treeSetTypeVar = TreeSet.class.getTypeParameters()[0];
526545 Assert.assertTrue(typeVarAssigns.containsKey(treeSetTypeVar));
527546 Assert.assertEquals(iterableType.getActualTypeArguments()[0], typeVarAssigns
528547 .get(treeSetTypeVar));
530549
531550 @Test
532551 public void testGetRawType() throws SecurityException, NoSuchFieldException {
533 Type stringParentFieldType = GenericTypeHolder.class.getDeclaredField("stringParent")
552 final Type stringParentFieldType = GenericTypeHolder.class.getDeclaredField("stringParent")
534553 .getGenericType();
535 Type integerParentFieldType = GenericTypeHolder.class.getDeclaredField("integerParent")
554 final Type integerParentFieldType = GenericTypeHolder.class.getDeclaredField("integerParent")
536555 .getGenericType();
537 Type foosFieldType = GenericTypeHolder.class.getDeclaredField("foos").getGenericType();
538 Type genericParentT = GenericParent.class.getTypeParameters()[0];
556 final Type foosFieldType = GenericTypeHolder.class.getDeclaredField("foos").getGenericType();
557 final Type genericParentT = GenericParent.class.getTypeParameters()[0];
539558 Assert.assertEquals(GenericParent.class, TypeUtils.getRawType(stringParentFieldType, null));
540559 Assert
541560 .assertEquals(GenericParent.class, TypeUtils.getRawType(integerParentFieldType,
581600
582601 @Test
583602 public void testIsArrayGenericTypes() throws Exception {
584 Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
603 final Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
585604 List.class, List.class, List.class, List.class, List[].class, List[].class,
586605 List[].class, List[].class, List[].class, List[].class, List[].class);
587606
588 Type[] types = method.getGenericParameterTypes();
607 final Type[] types = method.getGenericParameterTypes();
589608
590609 Assert.assertFalse(TypeUtils.isArrayType(types[0]));
591610 Assert.assertFalse(TypeUtils.isArrayType(types[1]));
626645
627646 @Test
628647 public void testGetArrayComponentType() throws Exception {
629 Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
648 final Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
630649 List.class, List.class, List.class, List.class, List[].class, List[].class,
631650 List[].class, List[].class, List[].class, List[].class, List[].class);
632651
633 Type[] types = method.getGenericParameterTypes();
652 final Type[] types = method.getGenericParameterTypes();
634653
635654 Assert.assertNull(TypeUtils.getArrayComponentType(types[0]));
636655 Assert.assertNull(TypeUtils.getArrayComponentType(types[1]));
648667 Assert.assertEquals(types[6], TypeUtils.getArrayComponentType(types[13]));
649668 }
650669
670 @Test
671 public void testLang820() throws Exception {
672 final Type[] typeArray = {String.class, String.class};
673 final Type[] expectedArray = {String.class};
674 Assert.assertArrayEquals(expectedArray, TypeUtils.normalizeUpperBounds(typeArray));
675 }
676
677 @Test
678 public void testParameterize() throws Exception {
679 final ParameterizedType stringComparableType = TypeUtils.parameterize(Comparable.class, String.class);
680 Assert.assertTrue(TypeUtils.equals(getClass().getField("stringComparable").getGenericType(),
681 stringComparableType));
682 Assert.assertEquals("java.lang.Comparable<java.lang.String>", stringComparableType.toString());
683 }
684
685 @Test
686 public void testParameterizeWithOwner() throws Exception {
687 final Type owner = TypeUtils.parameterize(TypeUtilsTest.class, String.class);
688 final ParameterizedType dat2Type = TypeUtils.parameterizeWithOwner(owner, That.class, String.class, String.class);
689 Assert.assertTrue(TypeUtils.equals(getClass().getField("dat2").getGenericType(), dat2Type));
690 }
691
692 @Test
693 public void testWildcardType() throws Exception {
694 final WildcardType simpleWildcard = TypeUtils.wildcardType().withUpperBounds(String.class).build();
695 final Field cClass = AClass.class.getField("cClass");
696 Assert.assertTrue(TypeUtils.equals(((ParameterizedType) cClass.getGenericType()).getActualTypeArguments()[0],
697 simpleWildcard));
698 }
699
700 @Test
701 public void testGenericArrayType() throws Exception {
702 final Type expected = getClass().getField("intWildcardComparable").getGenericType();
703 final GenericArrayType actual =
704 TypeUtils.genericArrayType(TypeUtils.parameterize(Comparable.class, TypeUtils.wildcardType()
705 .withUpperBounds(Integer.class).build()));
706 Assert.assertTrue(TypeUtils.equals(expected, actual));
707 Assert.assertEquals("java.lang.Comparable<? extends java.lang.Integer>[]", actual.toString());
708 }
709
710 @Test
711 public void testToLongString() {
712 Assert.assertEquals(getClass().getName() + ":B", TypeUtils.toLongString(getClass().getTypeParameters()[0]));
713 }
714
715 @Test
716 public void testWrap() {
717 final Type t = getClass().getTypeParameters()[0];
718 Assert.assertTrue(TypeUtils.equals(t, TypeUtils.wrap(t).getType()));
719
720 Assert.assertEquals(String.class, TypeUtils.wrap(String.class).getType());
721 }
722
651723 public Iterable<? extends Map<Integer, ? extends Collection<?>>> iterable;
652724
653725 public static <G extends Comparable<G>> G stub() {
678750 //raw types, where used, are used purposely
679751 class AClass extends AAClass<String>.BBClass<Number> {
680752
681 public AClass(AAClass<String> enclosingInstance) {
753 public AClass(final AAClass<String> enclosingInstance) {
682754 enclosingInstance.super();
683755 }
684756
1616 package org.apache.commons.lang3.reflect.testbed;
1717
1818 /**
19 * @version $Id: Ambig.java 1088899 2011-04-05 05:31:27Z bayard $
19 * @version $Id: Ambig.java 1510301 2013-08-04 18:40:48Z mbenson $
2020 */
2121 public class Ambig implements Foo, Bar {
22
23 @Override
24 public void doIt() {
25 }
2226 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect.testbed;
17
18 /**
19 *
20 */
21 public class AnotherChild extends AnotherParent {
22 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect.testbed;
17
18 /**
19 *
20 */
21 public class AnotherParent {
22 }
1616 package org.apache.commons.lang3.reflect.testbed;
1717
1818 /**
19 * @version $Id: Bar.java 1088899 2011-04-05 05:31:27Z bayard $
19 * @version $Id: Bar.java 1510301 2013-08-04 18:40:48Z mbenson $
2020 */
2121 public interface Bar {
2222 public static final String VALUE = "bar";
23
24 void doIt();
2325 }
1616 package org.apache.commons.lang3.reflect.testbed;
1717
1818 /**
19 * @version $Id: Foo.java 1088899 2011-04-05 05:31:27Z bayard $
19 * @version $Id: Foo.java 1510301 2013-08-04 18:40:48Z mbenson $
2020 */
2121 public interface Foo {
2222 public static final String VALUE = "foo";
23
24 void doIt();
2325 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect.testbed;
17
18 public interface GenericConsumer<T> {
19 void consume(T t);
20 }
1717
1818 /**
1919 * Class declaring a parameter variable.
20 * @version $Id: GenericParent.java 1088899 2011-04-05 05:31:27Z bayard $
20 * @version $Id: GenericParent.java 1510301 2013-08-04 18:40:48Z mbenson $
2121 */
22 public class GenericParent<T> {
22 public class GenericParent<T> implements GenericConsumer<T> {
23
24 @Override
25 public void consume(T t) {
26 }
2327
2428 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.reflect.testbed;
17
18 /**
19 *
20 */
21 public class Grandchild extends AnotherChild {
22 }
1616 package org.apache.commons.lang3.reflect.testbed;
1717
1818 /**
19 * @version $Id: Parent.java 1088899 2011-04-05 05:31:27Z bayard $
19 * @version $Id: Parent.java 1510301 2013-08-04 18:40:48Z mbenson $
2020 */
2121 class Parent implements Foo {
2222 public String s = "s";
2323 protected boolean b = false;
2424 int i = 0;
2525 @SuppressWarnings("unused")
26 private double d = 0.0;
26 private final double d = 0.0;
27
28 @Override
29 public void doIt() {
30 }
2731 }
1616 package org.apache.commons.lang3.reflect.testbed;
1717
1818 /**
19 * @version $Id: PrivatelyShadowedChild.java 1088899 2011-04-05 05:31:27Z bayard $
19 * @version $Id: PrivatelyShadowedChild.java 1436767 2013-01-22 07:05:41Z ggregory $
2020 */
2121 @SuppressWarnings({ "unused", "hiding" }) // deliberate re-use of variable names
2222 public class PrivatelyShadowedChild extends Parent {
23 private String s = "ss";
24 private boolean b = true;
25 private int i = 1;
26 private double d = 1.0;
23 private final String s = "ss";
24 private final boolean b = true;
25 private final int i = 1;
26 private final double d = 1.0;
2727 }
1616 package org.apache.commons.lang3.reflect.testbed;
1717
1818 /**
19 * @version $Id: StaticContainer.java 1088899 2011-04-05 05:31:27Z bayard $
19 * @version $Id: StaticContainer.java 1546799 2013-12-01 10:34:02Z mcucchiara $
2020 */
2121 public class StaticContainer {
2222 public static final Object IMMUTABLE_PUBLIC = "public";
2323 protected static final Object IMMUTABLE_PROTECTED = "protected";
24 @SuppressWarnings("unused")
2425 static final Object IMMUTABLE_PACKAGE = "";
2526 @SuppressWarnings("unused")
2627 private static final Object IMMUTABLE_PRIVATE = "private";
28
29 /**
30 * This final modifier of this field is meant to be removed by a test.
31 * Using this field may produce unpredictable results.
32 */
33 @SuppressWarnings("unused")
34 private static final Object IMMUTABLE_PRIVATE_2 = "private";
2735
2836 public static Object mutablePublic;
2937 protected static Object mutableProtected;
1717
1818 /**
1919 * {@link GenericParent} subclass that explicitly specifies <T> as {@link String}.
20 * @version $Id: StringParameterizedChild.java 1088899 2011-04-05 05:31:27Z bayard $
20 * @version $Id: StringParameterizedChild.java 1510301 2013-08-04 18:40:48Z mbenson $
2121 */
2222 public class StringParameterizedChild extends GenericParent<String> {
23
23 @Override
24 public void consume(String t) {
25 super.consume(t);
26 }
2427 }
1616
1717 package org.apache.commons.lang3.text;
1818
19 import org.junit.Test;
20 import static org.junit.Assert.*;
1921 import java.text.FieldPosition;
2022 import java.text.Format;
2123 import java.text.ParsePosition;
2224 import java.text.SimpleDateFormat;
2325 import java.util.Locale;
2426
25 import junit.framework.TestCase;
26
2727 /**
2828 * Unit tests for {@link org.apache.commons.lang3.text.CompositeFormat}.
2929 */
30 public class CompositeFormatTest extends TestCase {
31
32 /**
33 * Create a new test case with the specified name.
34 *
35 * @param name
36 * name
37 */
38 public CompositeFormatTest(String name) {
39 super(name);
40 }
41
30 public class CompositeFormatTest {
4231
4332 /**
4433 * Ensures that the parse/format separation is correctly maintained.
4534 */
35 @Test
4636 public void testCompositeFormat() {
4737
48 Format parser = new Format() {
49 @Override
50 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
38 final Format parser = new Format() {
39 private static final long serialVersionUID = 1L;
40
41 @Override
42 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
5143 throw new UnsupportedOperationException("Not implemented");
5244 }
5345
5446 @Override
55 public Object parseObject(String source, ParsePosition pos) {
47 public Object parseObject(final String source, final ParsePosition pos) {
5648 return null; // do nothing
5749 }
5850 };
5951
60 Format formatter = new Format() {
61 @Override
62 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
52 final Format formatter = new Format() {
53 private static final long serialVersionUID = 1L;
54
55 @Override
56 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
6357 return null; // do nothing
6458 }
6559
6660 @Override
67 public Object parseObject(String source, ParsePosition pos) {
61 public Object parseObject(final String source, final ParsePosition pos) {
6862 throw new UnsupportedOperationException("Not implemented");
6963 }
7064 };
7165
72 CompositeFormat composite = new CompositeFormat(parser, formatter);
66 final CompositeFormat composite = new CompositeFormat(parser, formatter);
7367
7468 composite.parseObject("", null);
7569 composite.format(new Object(), new StringBuffer(), null);
7771 assertEquals( "Formatter get method incorrectly implemented", formatter, composite.getFormatter() );
7872 }
7973
74 @Test
8075 public void testUsage() throws Exception {
81 Format f1 = new SimpleDateFormat("MMddyyyy", Locale.ENGLISH);
82 Format f2 = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
83 CompositeFormat c = new CompositeFormat(f1, f2);
84 String testString = "January 3, 2005";
76 final Format f1 = new SimpleDateFormat("MMddyyyy", Locale.ENGLISH);
77 final Format f2 = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
78 final CompositeFormat c = new CompositeFormat(f1, f2);
79 final String testString = "January 3, 2005";
8580 assertEquals(testString, c.format(c.parseObject("01032005")));
8681 assertEquals(testString, c.reformat("01032005"));
8782 }
1515 */
1616 package org.apache.commons.lang3.text;
1717
18 import org.junit.Test;
19 import org.junit.Before;
20 import static org.junit.Assert.*;
1821 import static org.apache.commons.lang3.JavaVersion.JAVA_1_4;
1922
2023 import java.text.ChoiceFormat;
3235 import java.util.Locale;
3336 import java.util.Map;
3437
35 import junit.framework.TestCase;
36
3738 import org.apache.commons.lang3.SystemUtils;
3839
3940 /**
4041 * Test case for {@link ExtendedMessageFormat}.
4142 *
4243 * @since 2.4
43 * @version $Id: ExtendedMessageFormatTest.java 1153490 2011-08-03 13:53:35Z ggregory $
44 * @version $Id: ExtendedMessageFormatTest.java 1535547 2013-10-24 20:54:34Z bayard $
4445 */
45 public class ExtendedMessageFormatTest extends TestCase {
46 public class ExtendedMessageFormatTest {
4647
4748 private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>();
4849
49 /**
50 * Create a new test case.
51 *
52 * @param name The name of the test
53 */
54 public ExtendedMessageFormatTest(String name) {
55 super(name);
56 }
57
58 @Override
59 protected void setUp() throws Exception {
60 super.setUp();
50 @Before
51 public void setUp() throws Exception {
6152 registry.put("lower", new LowerCaseFormatFactory());
6253 registry.put("upper", new UpperCaseFormatFactory());
6354 }
6556 /**
6657 * Test extended formats.
6758 */
59 @Test
6860 public void testExtendedFormats() {
69 String pattern = "Lower: {0,lower} Upper: {1,upper}";
70 ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
61 final String pattern = "Lower: {0,lower} Upper: {1,upper}";
62 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
7163 assertPatternsEqual("TOPATTERN", pattern, emf.toPattern());
7264 assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "bar"}));
7365 assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"Foo", "Bar"}));
7971 /**
8072 * Test Bug LANG-477 - out of memory error with escaped quote
8173 */
74 @Test
8275 public void testEscapedQuote_LANG_477() {
83 String pattern = "it''s a {0,lower} 'test'!";
84 ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
76 final String pattern = "it''s a {0,lower} 'test'!";
77 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
8578 assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"}));
8679 }
8780
8881 /**
82 * Test Bug LANG-917 - IndexOutOfBoundsException and/or infinite loop when using a choice pattern
83 */
84 @Test
85 public void testEmbeddedPatternInChoice() {
86 final String pattern = "Hi {0,lower}, got {1,choice,0#none|1#one|1<{1,number}}, {2,upper}!";
87 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
88 assertEquals(emf.format(new Object[] {"there", 3, "great"}), "Hi there, got 3, GREAT!");
89 }
90
91 /**
8992 * Test extended and built in formats.
9093 */
94 @Test
9195 public void testExtendedAndBuiltInFormats() {
92 Calendar cal = Calendar.getInstance();
96 final Calendar cal = Calendar.getInstance();
9397 cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05);
94 Object[] args = new Object[] {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
95 String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
96 String extendedPattern = "Name: {0,upper} ";
97 String pattern = extendedPattern + builtinsPattern;
98
99 HashSet<Locale> testLocales = new HashSet<Locale>();
98 final Object[] args = new Object[] {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
99 final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
100 final String extendedPattern = "Name: {0,upper} ";
101 final String pattern = extendedPattern + builtinsPattern;
102
103 final HashSet<Locale> testLocales = new HashSet<Locale>();
100104 testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales()));
101105 testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales()));
102106 testLocales.add(null);
103107
104 for (Locale locale : testLocales) {
105 MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
106 String expectedPattern = extendedPattern + builtins.toPattern();
108 for (final Locale locale : testLocales) {
109 final MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
110 final String expectedPattern = extendedPattern + builtins.toPattern();
107111 DateFormat df = null;
108112 NumberFormat nf = null;
109113 ExtendedMessageFormat emf = null;
116120 nf = NumberFormat.getCurrencyInstance(locale);
117121 emf = new ExtendedMessageFormat(pattern, locale, registry);
118122 }
119 StringBuffer expected = new StringBuffer();
123 final StringBuilder expected = new StringBuilder();
120124 expected.append("Name: ");
121125 expected.append(args[0].toString().toUpperCase());
122126 expected.append(" DOB: ");
186190 /**
187191 * Test the built in choice format.
188192 */
193 @Test
189194 public void testBuiltInChoiceFormat() {
190 Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")};
195 final Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")};
191196 String choicePattern = null;
192 Locale[] availableLocales = ChoiceFormat.getAvailableLocales();
197 final Locale[] availableLocales = ChoiceFormat.getAvailableLocales();
193198
194199 choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
195 for (Object value : values) {
200 for (final Object value : values) {
196201 checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales);
197202 }
198203
199204 choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}";
200 for (Object value : values) {
205 for (final Object value : values) {
201206 checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales);
202207 }
203208 }
205210 /**
206211 * Test the built in date/time formats
207212 */
213 @Test
208214 public void testBuiltInDateTimeFormat() {
209 Calendar cal = Calendar.getInstance();
215 final Calendar cal = Calendar.getInstance();
210216 cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05);
211 Object[] args = new Object[] {cal.getTime()};
212 Locale[] availableLocales = DateFormat.getAvailableLocales();
217 final Object[] args = new Object[] {cal.getTime()};
218 final Locale[] availableLocales = DateFormat.getAvailableLocales();
213219
214220 checkBuiltInFormat("1: {0,date,short}", args, availableLocales);
215221 checkBuiltInFormat("2: {0,date,medium}", args, availableLocales);
225231 checkBuiltInFormat("12: {0,time}", args, availableLocales);
226232 }
227233
234 @Test
228235 public void testOverriddenBuiltinFormat() {
229 Calendar cal = Calendar.getInstance();
236 final Calendar cal = Calendar.getInstance();
230237 cal.set(2007, Calendar.JANUARY, 23);
231 Object[] args = new Object[] {cal.getTime()};
232 Locale[] availableLocales = DateFormat.getAvailableLocales();
233 Map<String, ? extends FormatFactory> registry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());
238 final Object[] args = new Object[] {cal.getTime()};
239 final Locale[] availableLocales = DateFormat.getAvailableLocales();
240 final Map<String, ? extends FormatFactory> dateRegistry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());
234241
235242 //check the non-overridden builtins:
236 checkBuiltInFormat("1: {0,date}", registry, args, availableLocales);
237 checkBuiltInFormat("2: {0,date,medium}", registry, args, availableLocales);
238 checkBuiltInFormat("3: {0,date,long}", registry, args, availableLocales);
239 checkBuiltInFormat("4: {0,date,full}", registry, args, availableLocales);
240 checkBuiltInFormat("5: {0,date,d MMM yy}", registry, args, availableLocales);
243 checkBuiltInFormat("1: {0,date}", dateRegistry, args, availableLocales);
244 checkBuiltInFormat("2: {0,date,medium}", dateRegistry, args, availableLocales);
245 checkBuiltInFormat("3: {0,date,long}", dateRegistry, args, availableLocales);
246 checkBuiltInFormat("4: {0,date,full}", dateRegistry, args, availableLocales);
247 checkBuiltInFormat("5: {0,date,d MMM yy}", dateRegistry, args, availableLocales);
241248
242249 //check the overridden format:
243250 for (int i = -1; i < availableLocales.length; i++) {
244 Locale locale = i < 0 ? null : availableLocales[i];
245 MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
246 String pattern = "{0,date,short}";
247 ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, registry);
251 final Locale locale = i < 0 ? null : availableLocales[i];
252 final MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
253 final String pattern = "{0,date,short}";
254 final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, dateRegistry);
248255 assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args));
249256 assertEquals("overridden date,short pattern", pattern, dateShort.toPattern());
250257 }
253260 /**
254261 * Test the built in number formats.
255262 */
263 @Test
256264 public void testBuiltInNumberFormat() {
257 Object[] args = new Object[] {Double.valueOf("6543.21")};
258 Locale[] availableLocales = NumberFormat.getAvailableLocales();
265 final Object[] args = new Object[] {Double.valueOf("6543.21")};
266 final Locale[] availableLocales = NumberFormat.getAvailableLocales();
259267 checkBuiltInFormat("1: {0,number}", args, availableLocales);
260268 checkBuiltInFormat("2: {0,number,integer}", args, availableLocales);
261269 checkBuiltInFormat("3: {0,number,currency}", args, availableLocales);
266274 /**
267275 * Test equals() and hashcode.
268276 */
277 @Test
269278 public void testEqualsHashcode() {
270 Map<String, ? extends FormatFactory> registry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory());
271 Map<String, ? extends FormatFactory> otherRegitry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory());
272
273 String pattern = "Pattern: {0,testfmt}";
274 ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, registry);
279 final Map<String, ? extends FormatFactory> fmtRegistry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory());
280 final Map<String, ? extends FormatFactory> otherRegitry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory());
281
282 final String pattern = "Pattern: {0,testfmt}";
283 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
275284
276285 ExtendedMessageFormat other = null;
277286
280289 assertTrue("same, hashcode()", emf.hashCode() == emf.hashCode());
281290
282291 // Equal Object
283 other = new ExtendedMessageFormat(pattern, Locale.US, registry);
292 other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
284293 assertTrue("equal, equals()", emf.equals(other));
285294 assertTrue("equal, hashcode()", emf.hashCode() == other.hashCode());
286295
287296 // Different Class
288 other = new OtherExtendedMessageFormat(pattern, Locale.US, registry);
297 other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
289298 assertFalse("class, equals()", emf.equals(other));
290299 assertTrue("class, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode
291300
292301 // Different pattern
293 other = new ExtendedMessageFormat("X" + pattern, Locale.US, registry);
302 other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry);
294303 assertFalse("pattern, equals()", emf.equals(other));
295304 assertFalse("pattern, hashcode()", emf.hashCode() == other.hashCode());
296305
300309 assertFalse("registry, hashcode()", emf.hashCode() == other.hashCode());
301310
302311 // Different Locale
303 other = new ExtendedMessageFormat(pattern, Locale.FRANCE, registry);
312 other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry);
304313 assertFalse("locale, equals()", emf.equals(other));
305314 assertTrue("locale, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode
306315 }
311320 * @param args MessageFormat arguments
312321 * @param locales to test
313322 */
314 private void checkBuiltInFormat(String pattern, Object[] args, Locale[] locales) {
323 private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales) {
315324 checkBuiltInFormat(pattern, null, args, locales);
316325 }
317326
318327 /**
319328 * Test a built in format for the specified Locales, plus <code>null</code> Locale.
320329 * @param pattern MessageFormat pattern
321 * @param registry FormatFactory registry to use
330 * @param fmtRegistry FormatFactory registry to use
322331 * @param args MessageFormat arguments
323332 * @param locales to test
324333 */
325 private void checkBuiltInFormat(String pattern, Map<String, ?> registry, Object[] args, Locale[] locales) {
326 checkBuiltInFormat(pattern, registry, args, (Locale) null);
327 for (Locale locale : locales) {
328 checkBuiltInFormat(pattern, registry, args, locale);
334 private void checkBuiltInFormat(final String pattern, final Map<String, ?> fmtRegistry, final Object[] args, final Locale[] locales) {
335 checkBuiltInFormat(pattern, fmtRegistry, args, (Locale) null);
336 for (final Locale locale : locales) {
337 checkBuiltInFormat(pattern, fmtRegistry, args, locale);
329338 }
330339 }
331340
333342 * Create an ExtendedMessageFormat for the specified pattern and locale and check the
334343 * formated output matches the expected result for the parameters.
335344 * @param pattern string
336 * @param registry map
345 * @param registryUnused map (currently unused)
337346 * @param args Object[]
338347 * @param locale Locale
339348 */
340 private void checkBuiltInFormat(String pattern, Map<String, ?> registry, Object[] args, Locale locale) {
341 StringBuffer buffer = new StringBuffer();
349 private void checkBuiltInFormat(final String pattern, final Map<String, ?> registryUnused, final Object[] args, final Locale locale) {
350 final StringBuilder buffer = new StringBuilder();
342351 buffer.append("Pattern=[");
343352 buffer.append(pattern);
344353 buffer.append("], locale=[");
345354 buffer.append(locale);
346355 buffer.append("]");
347 MessageFormat mf = createMessageFormat(pattern, locale);
356 final MessageFormat mf = createMessageFormat(pattern, locale);
348357 // System.out.println(buffer + ", result=[" + mf.format(args) +"]");
349358 ExtendedMessageFormat emf = null;
350359 if (locale == null) {
357366 }
358367
359368 //can't trust what MessageFormat does with toPattern() pre 1.4:
360 private void assertPatternsEqual(String message, String expected, String actual) {
369 private void assertPatternsEqual(final String message, final String expected, final String actual) {
361370 if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) {
362371 assertEquals(message, expected, actual);
363372 }
369378 * @param locale Locale
370379 * @return MessageFormat
371380 */
372 private MessageFormat createMessageFormat(String pattern, Locale locale) {
373 MessageFormat result = new MessageFormat(pattern);
381 private MessageFormat createMessageFormat(final String pattern, final Locale locale) {
382 final MessageFormat result = new MessageFormat(pattern);
374383 if (locale != null) {
375384 result.setLocale(locale);
376385 result.applyPattern(pattern);
384393 * {@link Format} implementation which converts to lower case.
385394 */
386395 private static class LowerCaseFormat extends Format {
387 @Override
388 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
396 private static final long serialVersionUID = 1L;
397
398 @Override
399 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
389400 return toAppendTo.append(((String)obj).toLowerCase());
390401 }
391402 @Override
392 public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();}
403 public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();}
393404 }
394405
395406 /**
396407 * {@link Format} implementation which converts to upper case.
397408 */
398409 private static class UpperCaseFormat extends Format {
399 @Override
400 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
410 private static final long serialVersionUID = 1L;
411
412 @Override
413 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
401414 return toAppendTo.append(((String)obj).toUpperCase());
402415 }
403416 @Override
404 public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();}
417 public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();}
405418 }
406419
407420
411424 */
412425 private static class LowerCaseFormatFactory implements FormatFactory {
413426 private static final Format LOWER_INSTANCE = new LowerCaseFormat();
414 public Format getFormat(String name, String arguments, Locale locale) {
427 @Override
428 public Format getFormat(final String name, final String arguments, final Locale locale) {
415429 return LOWER_INSTANCE;
416430 }
417431 }
420434 */
421435 private static class UpperCaseFormatFactory implements FormatFactory {
422436 private static final Format UPPER_INSTANCE = new UpperCaseFormat();
423 public Format getFormat(String name, String arguments, Locale locale) {
437 @Override
438 public Format getFormat(final String name, final String arguments, final Locale locale) {
424439 return UPPER_INSTANCE;
425440 }
426441 }
428443 * {@link FormatFactory} implementation to override date format "short" to "default".
429444 */
430445 private static class OverrideShortDateFormatFactory implements FormatFactory {
431 public Format getFormat(String name, String arguments, Locale locale) {
446 @Override
447 public Format getFormat(final String name, final String arguments, final Locale locale) {
432448 return !"short".equals(arguments) ? null
433449 : locale == null ? DateFormat
434450 .getDateInstance(DateFormat.DEFAULT) : DateFormat
440456 * Alternative ExtendedMessageFormat impl.
441457 */
442458 private static class OtherExtendedMessageFormat extends ExtendedMessageFormat {
443 public OtherExtendedMessageFormat(String pattern, Locale locale,
444 Map<String, ? extends FormatFactory> registry) {
459 private static final long serialVersionUID = 1L;
460
461 public OtherExtendedMessageFormat(final String pattern, final Locale locale,
462 final Map<String, ? extends FormatFactory> registry) {
445463 super(pattern, locale, registry);
446464 }
447465
2525 /**
2626 * Unit tests {@link FormattableUtils}.
2727 *
28 * @version $Id: FormattableUtilsTest.java 1127546 2011-05-25 14:44:04Z scolebourne $
28 * @version $Id: FormattableUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2929 */
3030 public class FormattableUtilsTest {
3131
4545
4646 @Test
4747 public void testAlternatePadCharacter() {
48 char pad='_';
48 final char pad='_';
4949 assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, pad).toString());
5050 assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, pad).toString());
5151 assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, pad).toString());
1616
1717 package org.apache.commons.lang3.text;
1818
19 import org.junit.Test;
20 import static org.junit.Assert.*;
21
22 import java.text.DecimalFormatSymbols;
1923 import java.util.Arrays;
2024 import java.util.Collection;
2125 import java.util.Collections;
2226 import java.util.Iterator;
2327
24 import junit.framework.TestCase;
25
2628 import org.apache.commons.lang3.SystemUtils;
2729
2830 /**
2931 * Unit tests for {@link org.apache.commons.lang3.text.StrBuilder}.
3032 *
31 * @version $Id: StrBuilderAppendInsertTest.java 1153484 2011-08-03 13:39:42Z ggregory $
33 * @version $Id: StrBuilderAppendInsertTest.java 1533541 2013-10-18 16:33:52Z sebb $
3234 */
33 public class StrBuilderAppendInsertTest extends TestCase {
35 public class StrBuilderAppendInsertTest {
3436
3537 /** The system line separator. */
3638 private static final String SEP = SystemUtils.LINE_SEPARATOR;
4345 }
4446 };
4547
46 /**
47 * Create a new test case with the specified name.
48 *
49 * @param name the name
50 */
51 public StrBuilderAppendInsertTest(String name) {
52 super(name);
53 }
54
55 //-----------------------------------------------------------------------
48 //-----------------------------------------------------------------------
49 @Test
5650 public void testAppendNewLine() {
5751 StrBuilder sb = new StrBuilder("---");
5852 sb.appendNewLine().append("+++");
6458 }
6559
6660 //-----------------------------------------------------------------------
61 @Test
6762 public void testAppendWithNullText() {
68 StrBuilder sb = new StrBuilder();
63 final StrBuilder sb = new StrBuilder();
6964 sb.setNullText("NULL");
7065 assertEquals("", sb.toString());
7166
9590 }
9691
9792 //-----------------------------------------------------------------------
93 @Test
9894 public void testAppend_Object() {
99 StrBuilder sb = new StrBuilder();
95 final StrBuilder sb = new StrBuilder();
10096 sb.appendNull();
10197 assertEquals("", sb.toString());
10298
117113
118114 sb.append((CharSequence) "Seq");
119115 assertEquals("foobazyesSeq", sb.toString());
120 }
121
122 //-----------------------------------------------------------------------
116
117 sb.append(new StringBuilder("bld")); // Check it supports StringBuilder
118 assertEquals("foobazyesSeqbld", sb.toString());
119 }
120
121 //-----------------------------------------------------------------------
122 @Test
123 public void testAppend_StringBuilder() {
124 StrBuilder sb = new StrBuilder();
125 sb.setNullText("NULL").append((String) null);
126 assertEquals("NULL", sb.toString());
127
128 sb = new StrBuilder();
129 sb.append(new StringBuilder("foo"));
130 assertEquals("foo", sb.toString());
131
132 sb.append(new StringBuilder(""));
133 assertEquals("foo", sb.toString());
134
135 sb.append(new StringBuilder("bar"));
136 assertEquals("foobar", sb.toString());
137 }
138
139 //-----------------------------------------------------------------------
140 @Test
123141 public void testAppend_String() {
124142 StrBuilder sb = new StrBuilder();
125143 sb.setNullText("NULL").append((String) null);
137155 }
138156
139157 //-----------------------------------------------------------------------
158 @Test
140159 public void testAppend_String_int_int() {
141160 StrBuilder sb = new StrBuilder();
142161 sb.setNullText("NULL").append((String) null, 0, 1);
149168 try {
150169 sb.append("bar", -1, 1);
151170 fail("append(char[], -1,) expected IndexOutOfBoundsException");
152 } catch (IndexOutOfBoundsException e) {
171 } catch (final IndexOutOfBoundsException e) {
153172 // expected
154173 }
155174
156175 try {
157176 sb.append("bar", 3, 1);
158177 fail("append(char[], 3,) expected IndexOutOfBoundsException");
159 } catch (IndexOutOfBoundsException e) {
178 } catch (final IndexOutOfBoundsException e) {
160179 // expected
161180 }
162181
163182 try {
164183 sb.append("bar", 1, -1);
165184 fail("append(char[],, -1) expected IndexOutOfBoundsException");
166 } catch (IndexOutOfBoundsException e) {
185 } catch (final IndexOutOfBoundsException e) {
167186 // expected
168187 }
169188
170189 try {
171190 sb.append("bar", 1, 3);
172191 fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
173 } catch (IndexOutOfBoundsException e) {
192 } catch (final IndexOutOfBoundsException e) {
174193 // expected
175194 }
176195
177196 try {
178197 sb.append("bar", -1, 3);
179198 fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
180 } catch (IndexOutOfBoundsException e) {
199 } catch (final IndexOutOfBoundsException e) {
181200 // expected
182201 }
183202
184203 try {
185204 sb.append("bar", 4, 0);
186205 fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
187 } catch (IndexOutOfBoundsException e) {
206 } catch (final IndexOutOfBoundsException e) {
188207 // expected
189208 }
190209
197216 sb.append( (CharSequence)"abcbardef", 4, 3);
198217 assertEquals("foobarard", sb.toString());
199218 }
200
201 //-----------------------------------------------------------------------
219
220 //-----------------------------------------------------------------------
221 @Test
222 public void testAppend_StringBuilder_int_int() {
223 StrBuilder sb = new StrBuilder();
224 sb.setNullText("NULL").append((String) null, 0, 1);
225 assertEquals("NULL", sb.toString());
226
227 sb = new StrBuilder();
228 sb.append(new StringBuilder("foo"), 0, 3);
229 assertEquals("foo", sb.toString());
230
231 try {
232 sb.append(new StringBuilder("bar"), -1, 1);
233 fail("append(StringBuilder, -1,) expected IndexOutOfBoundsException");
234 } catch (final IndexOutOfBoundsException e) {
235 // expected
236 }
237
238 try {
239 sb.append(new StringBuilder("bar"), 3, 1);
240 fail("append(StringBuilder, 3,) expected IndexOutOfBoundsException");
241 } catch (final IndexOutOfBoundsException e) {
242 // expected
243 }
244
245 try {
246 sb.append(new StringBuilder("bar"), 1, -1);
247 fail("append(StringBuilder,, -1) expected IndexOutOfBoundsException");
248 } catch (final IndexOutOfBoundsException e) {
249 // expected
250 }
251
252 try {
253 sb.append(new StringBuilder("bar"), 1, 3);
254 fail("append(StringBuilder, 1, 3) expected IndexOutOfBoundsException");
255 } catch (final IndexOutOfBoundsException e) {
256 // expected
257 }
258
259 try {
260 sb.append(new StringBuilder("bar"), -1, 3);
261 fail("append(StringBuilder, -1, 3) expected IndexOutOfBoundsException");
262 } catch (final IndexOutOfBoundsException e) {
263 // expected
264 }
265
266 try {
267 sb.append(new StringBuilder("bar"), 4, 0);
268 fail("append(StringBuilder, 4, 0) expected IndexOutOfBoundsException");
269 } catch (final IndexOutOfBoundsException e) {
270 // expected
271 }
272
273 sb.append(new StringBuilder("bar"), 3, 0);
274 assertEquals("foo", sb.toString());
275
276 sb.append(new StringBuilder("abcbardef"), 3, 3);
277 assertEquals("foobar", sb.toString());
278
279 sb.append( new StringBuilder("abcbardef"), 4, 3);
280 assertEquals("foobarard", sb.toString());
281 }
282
283 //-----------------------------------------------------------------------
284 @Test
202285 public void testAppend_StringBuffer() {
203286 StrBuilder sb = new StrBuilder();
204287 sb.setNullText("NULL").append((StringBuffer) null);
216299 }
217300
218301 //-----------------------------------------------------------------------
302 @Test
219303 public void testAppend_StringBuffer_int_int() {
220304 StrBuilder sb = new StrBuilder();
221305 sb.setNullText("NULL").append((StringBuffer) null, 0, 1);
228312 try {
229313 sb.append(new StringBuffer("bar"), -1, 1);
230314 fail("append(char[], -1,) expected IndexOutOfBoundsException");
231 } catch (IndexOutOfBoundsException e) {
315 } catch (final IndexOutOfBoundsException e) {
232316 // expected
233317 }
234318
235319 try {
236320 sb.append(new StringBuffer("bar"), 3, 1);
237321 fail("append(char[], 3,) expected IndexOutOfBoundsException");
238 } catch (IndexOutOfBoundsException e) {
322 } catch (final IndexOutOfBoundsException e) {
239323 // expected
240324 }
241325
242326 try {
243327 sb.append(new StringBuffer("bar"), 1, -1);
244328 fail("append(char[],, -1) expected IndexOutOfBoundsException");
245 } catch (IndexOutOfBoundsException e) {
329 } catch (final IndexOutOfBoundsException e) {
246330 // expected
247331 }
248332
249333 try {
250334 sb.append(new StringBuffer("bar"), 1, 3);
251335 fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
252 } catch (IndexOutOfBoundsException e) {
336 } catch (final IndexOutOfBoundsException e) {
253337 // expected
254338 }
255339
256340 try {
257341 sb.append(new StringBuffer("bar"), -1, 3);
258342 fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
259 } catch (IndexOutOfBoundsException e) {
343 } catch (final IndexOutOfBoundsException e) {
260344 // expected
261345 }
262346
263347 try {
264348 sb.append(new StringBuffer("bar"), 4, 0);
265349 fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
266 } catch (IndexOutOfBoundsException e) {
350 } catch (final IndexOutOfBoundsException e) {
267351 // expected
268352 }
269353
275359 }
276360
277361 //-----------------------------------------------------------------------
362 @Test
278363 public void testAppend_StrBuilder() {
279364 StrBuilder sb = new StrBuilder();
280365 sb.setNullText("NULL").append((StrBuilder) null);
292377 }
293378
294379 //-----------------------------------------------------------------------
380 @Test
295381 public void testAppend_StrBuilder_int_int() {
296382 StrBuilder sb = new StrBuilder();
297383 sb.setNullText("NULL").append((StrBuilder) null, 0, 1);
304390 try {
305391 sb.append(new StrBuilder("bar"), -1, 1);
306392 fail("append(char[], -1,) expected IndexOutOfBoundsException");
307 } catch (IndexOutOfBoundsException e) {
393 } catch (final IndexOutOfBoundsException e) {
308394 // expected
309395 }
310396
311397 try {
312398 sb.append(new StrBuilder("bar"), 3, 1);
313399 fail("append(char[], 3,) expected IndexOutOfBoundsException");
314 } catch (IndexOutOfBoundsException e) {
400 } catch (final IndexOutOfBoundsException e) {
315401 // expected
316402 }
317403
318404 try {
319405 sb.append(new StrBuilder("bar"), 1, -1);
320406 fail("append(char[],, -1) expected IndexOutOfBoundsException");
321 } catch (IndexOutOfBoundsException e) {
407 } catch (final IndexOutOfBoundsException e) {
322408 // expected
323409 }
324410
325411 try {
326412 sb.append(new StrBuilder("bar"), 1, 3);
327413 fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
328 } catch (IndexOutOfBoundsException e) {
414 } catch (final IndexOutOfBoundsException e) {
329415 // expected
330416 }
331417
332418 try {
333419 sb.append(new StrBuilder("bar"), -1, 3);
334420 fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
335 } catch (IndexOutOfBoundsException e) {
421 } catch (final IndexOutOfBoundsException e) {
336422 // expected
337423 }
338424
339425 try {
340426 sb.append(new StrBuilder("bar"), 4, 0);
341427 fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
342 } catch (IndexOutOfBoundsException e) {
428 } catch (final IndexOutOfBoundsException e) {
343429 // expected
344430 }
345431
351437 }
352438
353439 //-----------------------------------------------------------------------
440 @Test
354441 public void testAppend_CharArray() {
355442 StrBuilder sb = new StrBuilder();
356443 sb.setNullText("NULL").append((char[]) null);
365452 }
366453
367454 //-----------------------------------------------------------------------
455 @Test
368456 public void testAppend_CharArray_int_int() {
369457 StrBuilder sb = new StrBuilder();
370458 sb.setNullText("NULL").append((char[]) null, 0, 1);
377465 try {
378466 sb.append(new char[]{'b', 'a', 'r'}, -1, 1);
379467 fail("append(char[], -1,) expected IndexOutOfBoundsException");
380 } catch (IndexOutOfBoundsException e) {
468 } catch (final IndexOutOfBoundsException e) {
381469 // expected
382470 }
383471
384472 try {
385473 sb.append(new char[]{'b', 'a', 'r'}, 3, 1);
386474 fail("append(char[], 3,) expected IndexOutOfBoundsException");
387 } catch (IndexOutOfBoundsException e) {
475 } catch (final IndexOutOfBoundsException e) {
388476 // expected
389477 }
390478
391479 try {
392480 sb.append(new char[]{'b', 'a', 'r'}, 1, -1);
393481 fail("append(char[],, -1) expected IndexOutOfBoundsException");
394 } catch (IndexOutOfBoundsException e) {
482 } catch (final IndexOutOfBoundsException e) {
395483 // expected
396484 }
397485
398486 try {
399487 sb.append(new char[]{'b', 'a', 'r'}, 1, 3);
400488 fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
401 } catch (IndexOutOfBoundsException e) {
489 } catch (final IndexOutOfBoundsException e) {
402490 // expected
403491 }
404492
405493 try {
406494 sb.append(new char[]{'b', 'a', 'r'}, -1, 3);
407495 fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
408 } catch (IndexOutOfBoundsException e) {
496 } catch (final IndexOutOfBoundsException e) {
409497 // expected
410498 }
411499
412500 try {
413501 sb.append(new char[]{'b', 'a', 'r'}, 4, 0);
414502 fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
415 } catch (IndexOutOfBoundsException e) {
503 } catch (final IndexOutOfBoundsException e) {
416504 // expected
417505 }
418506
424512 }
425513
426514 //-----------------------------------------------------------------------
515 @Test
427516 public void testAppend_Boolean() {
428 StrBuilder sb = new StrBuilder();
517 final StrBuilder sb = new StrBuilder();
429518 sb.append(true);
430519 assertEquals("true", sb.toString());
431520
437526 }
438527
439528 //-----------------------------------------------------------------------
529 @Test
440530 public void testAppend_PrimitiveNumber() {
441 StrBuilder sb = new StrBuilder();
531 final StrBuilder sb = new StrBuilder();
442532 sb.append(0);
443533 assertEquals("0", sb.toString());
444534
453543 }
454544
455545 //-----------------------------------------------------------------------
546 @Test
547 public void testAppendln_FormattedString() {
548 final int[] count = new int[2];
549 final StrBuilder sb = new StrBuilder() {
550 private static final long serialVersionUID = 1L;
551
552 @Override
553 public StrBuilder append(final String str) {
554 count[0]++;
555 return super.append(str);
556 }
557 @Override
558 public StrBuilder appendNewLine() {
559 count[1]++;
560 return super.appendNewLine();
561 }
562 };
563 sb.appendln("Hello %s", "Alice");
564 assertEquals("Hello Alice" + SEP, sb.toString());
565 assertEquals(2, count[0]); // appendNewLine() calls append(String)
566 assertEquals(1, count[1]);
567 }
568
569 //-----------------------------------------------------------------------
570 @Test
456571 public void testAppendln_Object() {
457 StrBuilder sb = new StrBuilder();
572 final StrBuilder sb = new StrBuilder();
458573 sb.appendln((Object) null);
459574 assertEquals("" + SEP, sb.toString());
460575
466581 }
467582
468583 //-----------------------------------------------------------------------
584 @Test
469585 public void testAppendln_String() {
470586 final int[] count = new int[2];
471 StrBuilder sb = new StrBuilder() {
472 @Override
473 public StrBuilder append(String str) {
587 final StrBuilder sb = new StrBuilder() {
588 private static final long serialVersionUID = 1L;
589
590 @Override
591 public StrBuilder append(final String str) {
474592 count[0]++;
475593 return super.append(str);
476594 }
487605 }
488606
489607 //-----------------------------------------------------------------------
608 @Test
490609 public void testAppendln_String_int_int() {
491610 final int[] count = new int[2];
492 StrBuilder sb = new StrBuilder() {
493 @Override
494 public StrBuilder append(String str, int startIndex, int length) {
611 final StrBuilder sb = new StrBuilder() {
612 private static final long serialVersionUID = 1L;
613
614 @Override
615 public StrBuilder append(final String str, final int startIndex, final int length) {
495616 count[0]++;
496617 return super.append(str, startIndex, length);
497618 }
508629 }
509630
510631 //-----------------------------------------------------------------------
632 @Test
511633 public void testAppendln_StringBuffer() {
512634 final int[] count = new int[2];
513 StrBuilder sb = new StrBuilder() {
514 @Override
515 public StrBuilder append(StringBuffer str) {
635 final StrBuilder sb = new StrBuilder() {
636 private static final long serialVersionUID = 1L;
637
638 @Override
639 public StrBuilder append(final StringBuffer str) {
516640 count[0]++;
517641 return super.append(str);
518642 }
529653 }
530654
531655 //-----------------------------------------------------------------------
656 @Test
657 public void testAppendln_StringBuilder() {
658 final int[] count = new int[2];
659 final StrBuilder sb = new StrBuilder() {
660 private static final long serialVersionUID = 1L;
661
662 @Override
663 public StrBuilder append(final StringBuilder str) {
664 count[0]++;
665 return super.append(str);
666 }
667 @Override
668 public StrBuilder appendNewLine() {
669 count[1]++;
670 return super.appendNewLine();
671 }
672 };
673 sb.appendln(new StringBuilder("foo"));
674 assertEquals("foo" + SEP, sb.toString());
675 assertEquals(1, count[0]);
676 assertEquals(1, count[1]);
677 }
678
679 //-----------------------------------------------------------------------
680 @Test
532681 public void testAppendln_StringBuffer_int_int() {
533682 final int[] count = new int[2];
534 StrBuilder sb = new StrBuilder() {
535 @Override
536 public StrBuilder append(StringBuffer str, int startIndex, int length) {
683 final StrBuilder sb = new StrBuilder() {
684 private static final long serialVersionUID = 1L;
685
686 @Override
687 public StrBuilder append(final StringBuffer str, final int startIndex, final int length) {
537688 count[0]++;
538689 return super.append(str, startIndex, length);
539690 }
550701 }
551702
552703 //-----------------------------------------------------------------------
704 @Test
705 public void testAppendln_StringBuilder_int_int() {
706 final int[] count = new int[2];
707 final StrBuilder sb = new StrBuilder() {
708 private static final long serialVersionUID = 1L;
709
710 @Override
711 public StrBuilder append(final StringBuilder str, final int startIndex, final int length) {
712 count[0]++;
713 return super.append(str, startIndex, length);
714 }
715 @Override
716 public StrBuilder appendNewLine() {
717 count[1]++;
718 return super.appendNewLine();
719 }
720 };
721 sb.appendln(new StringBuilder("foo"), 0, 3);
722 assertEquals("foo" + SEP, sb.toString());
723 assertEquals(1, count[0]);
724 assertEquals(1, count[1]);
725 }
726
727 //-----------------------------------------------------------------------
728 @Test
553729 public void testAppendln_StrBuilder() {
554730 final int[] count = new int[2];
555 StrBuilder sb = new StrBuilder() {
556 @Override
557 public StrBuilder append(StrBuilder str) {
731 final StrBuilder sb = new StrBuilder() {
732 private static final long serialVersionUID = 1L;
733
734 @Override
735 public StrBuilder append(final StrBuilder str) {
558736 count[0]++;
559737 return super.append(str);
560738 }
571749 }
572750
573751 //-----------------------------------------------------------------------
752 @Test
574753 public void testAppendln_StrBuilder_int_int() {
575754 final int[] count = new int[2];
576 StrBuilder sb = new StrBuilder() {
577 @Override
578 public StrBuilder append(StrBuilder str, int startIndex, int length) {
755 final StrBuilder sb = new StrBuilder() {
756 private static final long serialVersionUID = 1L;
757
758 @Override
759 public StrBuilder append(final StrBuilder str, final int startIndex, final int length) {
579760 count[0]++;
580761 return super.append(str, startIndex, length);
581762 }
592773 }
593774
594775 //-----------------------------------------------------------------------
776 @Test
595777 public void testAppendln_CharArray() {
596778 final int[] count = new int[2];
597 StrBuilder sb = new StrBuilder() {
598 @Override
599 public StrBuilder append(char[] str) {
779 final StrBuilder sb = new StrBuilder() {
780 private static final long serialVersionUID = 1L;
781
782 @Override
783 public StrBuilder append(final char[] str) {
600784 count[0]++;
601785 return super.append(str);
602786 }
613797 }
614798
615799 //-----------------------------------------------------------------------
800 @Test
616801 public void testAppendln_CharArray_int_int() {
617802 final int[] count = new int[2];
618 StrBuilder sb = new StrBuilder() {
619 @Override
620 public StrBuilder append(char[] str, int startIndex, int length) {
803 final StrBuilder sb = new StrBuilder() {
804 private static final long serialVersionUID = 1L;
805
806 @Override
807 public StrBuilder append(final char[] str, final int startIndex, final int length) {
621808 count[0]++;
622809 return super.append(str, startIndex, length);
623810 }
634821 }
635822
636823 //-----------------------------------------------------------------------
824 @Test
637825 public void testAppendln_Boolean() {
638 StrBuilder sb = new StrBuilder();
826 final StrBuilder sb = new StrBuilder();
639827 sb.appendln(true);
640828 assertEquals("true" + SEP, sb.toString());
641829
645833 }
646834
647835 //-----------------------------------------------------------------------
836 @Test
648837 public void testAppendln_PrimitiveNumber() {
649 StrBuilder sb = new StrBuilder();
838 final StrBuilder sb = new StrBuilder();
650839 sb.appendln(0);
651840 assertEquals("0" + SEP, sb.toString());
652841
664853 }
665854
666855 //-----------------------------------------------------------------------
856 @Test
667857 public void testAppendPadding() {
668 StrBuilder sb = new StrBuilder();
858 final StrBuilder sb = new StrBuilder();
669859 sb.append("foo");
670860 assertEquals("foo", sb.toString());
671861
685875 }
686876
687877 //-----------------------------------------------------------------------
878 @Test
688879 public void testAppendFixedWidthPadLeft() {
689 StrBuilder sb = new StrBuilder();
880 final StrBuilder sb = new StrBuilder();
690881 sb.appendFixedWidthPadLeft("foo", -1, '-');
691882 assertEquals("", sb.toString());
692883
723914 }
724915
725916 //-----------------------------------------------------------------------
917 @Test
726918 public void testAppendFixedWidthPadLeft_int() {
727 StrBuilder sb = new StrBuilder();
919 final StrBuilder sb = new StrBuilder();
728920 sb.appendFixedWidthPadLeft(123, -1, '-');
729921 assertEquals("", sb.toString());
730922
756948 }
757949
758950 //-----------------------------------------------------------------------
951 @Test
759952 public void testAppendFixedWidthPadRight() {
760 StrBuilder sb = new StrBuilder();
953 final StrBuilder sb = new StrBuilder();
761954 sb.appendFixedWidthPadRight("foo", -1, '-');
762955 assertEquals("", sb.toString());
763956
794987 }
795988
796989 // See: http://issues.apache.org/jira/browse/LANG-299
990 @Test
797991 public void testLang299() {
798 StrBuilder sb = new StrBuilder(1);
992 final StrBuilder sb = new StrBuilder(1);
799993 sb.appendFixedWidthPadRight("foo", 1, '-');
800994 assertEquals("f", sb.toString());
801995 }
802996
803997 //-----------------------------------------------------------------------
998 @Test
804999 public void testAppendFixedWidthPadRight_int() {
805 StrBuilder sb = new StrBuilder();
1000 final StrBuilder sb = new StrBuilder();
8061001 sb.appendFixedWidthPadRight(123, -1, '-');
8071002 assertEquals("", sb.toString());
8081003
8341029 }
8351030
8361031 //-----------------------------------------------------------------------
1032 @Test
1033 public void testAppend_FormattedString() {
1034 StrBuilder sb;
1035
1036 sb = new StrBuilder();
1037 sb.append("Hi", (Object[]) null);
1038 assertEquals("Hi", sb.toString());
1039
1040 sb = new StrBuilder();
1041 sb.append("Hi", "Alice");
1042 assertEquals("Hi", sb.toString());
1043
1044 sb = new StrBuilder();
1045 sb.append("Hi %s", "Alice");
1046 assertEquals("Hi Alice", sb.toString());
1047
1048 sb = new StrBuilder();
1049 sb.append("Hi %s %,d", "Alice", 5000);
1050 // group separator depends on system locale
1051 char groupingSeparator = DecimalFormatSymbols.getInstance().getGroupingSeparator();
1052 String expected = "Hi Alice 5" + groupingSeparator + "000";
1053 assertEquals(expected, sb.toString());
1054 }
1055
1056 //-----------------------------------------------------------------------
1057 @Test
8371058 public void testAppendAll_Array() {
838 StrBuilder sb = new StrBuilder();
1059 final StrBuilder sb = new StrBuilder();
8391060 sb.appendAll((Object[]) null);
8401061 assertEquals("", sb.toString());
8411062
8461067 sb.clear();
8471068 sb.appendAll(new Object[]{"foo", "bar", "baz"});
8481069 assertEquals("foobarbaz", sb.toString());
849 }
850
851 //-----------------------------------------------------------------------
1070
1071 sb.clear();
1072 sb.appendAll("foo", "bar", "baz");
1073 assertEquals("foobarbaz", sb.toString());
1074 }
1075
1076 //-----------------------------------------------------------------------
1077 @Test
8521078 public void testAppendAll_Collection() {
853 StrBuilder sb = new StrBuilder();
1079 final StrBuilder sb = new StrBuilder();
8541080 sb.appendAll((Collection<?>) null);
8551081 assertEquals("", sb.toString());
8561082
8641090 }
8651091
8661092 //-----------------------------------------------------------------------
1093 @Test
8671094 public void testAppendAll_Iterator() {
868 StrBuilder sb = new StrBuilder();
1095 final StrBuilder sb = new StrBuilder();
8691096 sb.appendAll((Iterator<?>) null);
8701097 assertEquals("", sb.toString());
8711098
8791106 }
8801107
8811108 //-----------------------------------------------------------------------
1109 @Test
8821110 public void testAppendWithSeparators_Array() {
883 StrBuilder sb = new StrBuilder();
1111 final StrBuilder sb = new StrBuilder();
8841112 sb.appendWithSeparators((Object[]) null, ",");
8851113 assertEquals("", sb.toString());
8861114
9021130 }
9031131
9041132 //-----------------------------------------------------------------------
1133 @Test
9051134 public void testAppendWithSeparators_Collection() {
906 StrBuilder sb = new StrBuilder();
1135 final StrBuilder sb = new StrBuilder();
9071136 sb.appendWithSeparators((Collection<?>) null, ",");
9081137 assertEquals("", sb.toString());
9091138
9251154 }
9261155
9271156 //-----------------------------------------------------------------------
1157 @Test
9281158 public void testAppendWithSeparators_Iterator() {
929 StrBuilder sb = new StrBuilder();
1159 final StrBuilder sb = new StrBuilder();
9301160 sb.appendWithSeparators((Iterator<?>) null, ",");
9311161 assertEquals("", sb.toString());
9321162
9481178 }
9491179
9501180 //-----------------------------------------------------------------------
1181 @Test
9511182 public void testAppendWithSeparatorsWithNullText() {
952 StrBuilder sb = new StrBuilder();
1183 final StrBuilder sb = new StrBuilder();
9531184 sb.setNullText("null");
9541185 sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ",");
9551186 assertEquals("foo,null,baz", sb.toString());
9601191 }
9611192
9621193 //-----------------------------------------------------------------------
1194 @Test
9631195 public void testAppendSeparator_String() {
964 StrBuilder sb = new StrBuilder();
1196 final StrBuilder sb = new StrBuilder();
9651197 sb.appendSeparator(","); // no effect
9661198 assertEquals("", sb.toString());
9671199 sb.append("foo");
9711203 }
9721204
9731205 //-----------------------------------------------------------------------
1206 @Test
9741207 public void testAppendSeparator_String_String() {
975 StrBuilder sb = new StrBuilder();
1208 final StrBuilder sb = new StrBuilder();
9761209 final String startSeparator = "order by ";
9771210 final String standardSeparator = ",";
9781211 final String foo = "foo";
9931226 }
9941227
9951228 //-----------------------------------------------------------------------
1229 @Test
9961230 public void testAppendSeparator_char() {
997 StrBuilder sb = new StrBuilder();
1231 final StrBuilder sb = new StrBuilder();
9981232 sb.appendSeparator(','); // no effect
9991233 assertEquals("", sb.toString());
10001234 sb.append("foo");
10021236 sb.appendSeparator(',');
10031237 assertEquals("foo,", sb.toString());
10041238 }
1239 @Test
10051240 public void testAppendSeparator_char_char() {
1006 StrBuilder sb = new StrBuilder();
1241 final StrBuilder sb = new StrBuilder();
10071242 final char startSeparator = ':';
10081243 final char standardSeparator = ',';
10091244 final String foo = "foo";
10161251 }
10171252
10181253 //-----------------------------------------------------------------------
1254 @Test
10191255 public void testAppendSeparator_String_int() {
1020 StrBuilder sb = new StrBuilder();
1256 final StrBuilder sb = new StrBuilder();
10211257 sb.appendSeparator(",", 0); // no effect
10221258 assertEquals("", sb.toString());
10231259 sb.append("foo");
10301266 }
10311267
10321268 //-----------------------------------------------------------------------
1269 @Test
10331270 public void testAppendSeparator_char_int() {
1034 StrBuilder sb = new StrBuilder();
1271 final StrBuilder sb = new StrBuilder();
10351272 sb.appendSeparator(',', 0); // no effect
10361273 assertEquals("", sb.toString());
10371274 sb.append("foo");
10441281 }
10451282
10461283 //-----------------------------------------------------------------------
1284 @Test
10471285 public void testInsert() {
10481286
1049 StrBuilder sb = new StrBuilder();
1287 final StrBuilder sb = new StrBuilder();
10501288 sb.append("barbaz");
10511289 assertEquals("barbaz", sb.toString());
10521290
10531291 try {
10541292 sb.insert(-1, FOO);
10551293 fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
1056 } catch (IndexOutOfBoundsException e) {
1294 } catch (final IndexOutOfBoundsException e) {
10571295 // expected
10581296 }
10591297
10601298 try {
10611299 sb.insert(7, FOO);
10621300 fail("insert(7, Object) expected StringIndexOutOfBoundsException");
1063 } catch (IndexOutOfBoundsException e) {
1301 } catch (final IndexOutOfBoundsException e) {
10641302 // expected
10651303 }
10661304
10771315 try {
10781316 sb.insert(-1, "foo");
10791317 fail("insert(-1, String) expected StringIndexOutOfBoundsException");
1080 } catch (IndexOutOfBoundsException e) {
1318 } catch (final IndexOutOfBoundsException e) {
10811319 // expected
10821320 }
10831321
10841322 try {
10851323 sb.insert(7, "foo");
10861324 fail("insert(7, String) expected StringIndexOutOfBoundsException");
1087 } catch (IndexOutOfBoundsException e) {
1325 } catch (final IndexOutOfBoundsException e) {
10881326 // expected
10891327 }
10901328
11011339 try {
11021340 sb.insert(-1, new char[]{'f', 'o', 'o'});
11031341 fail("insert(-1, char[]) expected StringIndexOutOfBoundsException");
1104 } catch (IndexOutOfBoundsException e) {
1342 } catch (final IndexOutOfBoundsException e) {
11051343 // expected
11061344 }
11071345
11081346 try {
11091347 sb.insert(7, new char[]{'f', 'o', 'o'});
11101348 fail("insert(7, char[]) expected StringIndexOutOfBoundsException");
1111 } catch (IndexOutOfBoundsException e) {
1349 } catch (final IndexOutOfBoundsException e) {
11121350 // expected
11131351 }
11141352
11281366 try {
11291367 sb.insert(-1, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
11301368 fail("insert(-1, char[], 3, 3) expected StringIndexOutOfBoundsException");
1131 } catch (IndexOutOfBoundsException e) {
1369 } catch (final IndexOutOfBoundsException e) {
11321370 // expected
11331371 }
11341372
11351373 try {
11361374 sb.insert(7, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
11371375 fail("insert(7, char[], 3, 3) expected StringIndexOutOfBoundsException");
1138 } catch (IndexOutOfBoundsException e) {
1376 } catch (final IndexOutOfBoundsException e) {
11391377 // expected
11401378 }
11411379
11481386 try {
11491387 sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, -1, 3);
11501388 fail("insert(0, char[], -1, 3) expected StringIndexOutOfBoundsException");
1151 } catch (IndexOutOfBoundsException e) {
1389 } catch (final IndexOutOfBoundsException e) {
11521390 // expected
11531391 }
11541392
11551393 try {
11561394 sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 10, 3);
11571395 fail("insert(0, char[], 10, 3) expected StringIndexOutOfBoundsException");
1158 } catch (IndexOutOfBoundsException e) {
1396 } catch (final IndexOutOfBoundsException e) {
11591397 // expected
11601398 }
11611399
11621400 try {
11631401 sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, -1);
11641402 fail("insert(0, char[], 0, -1) expected StringIndexOutOfBoundsException");
1165 } catch (IndexOutOfBoundsException e) {
1403 } catch (final IndexOutOfBoundsException e) {
11661404 // expected
11671405 }
11681406
11691407 try {
11701408 sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 10);
11711409 fail("insert(0, char[], 0, 10) expected StringIndexOutOfBoundsException");
1172 } catch (IndexOutOfBoundsException e) {
1410 } catch (final IndexOutOfBoundsException e) {
11731411 // expected
11741412 }
11751413
11861424 try {
11871425 sb.insert(-1, true);
11881426 fail("insert(-1, boolean) expected StringIndexOutOfBoundsException");
1189 } catch (IndexOutOfBoundsException e) {
1427 } catch (final IndexOutOfBoundsException e) {
11901428 // expected
11911429 }
11921430
11931431 try {
11941432 sb.insert(7, true);
11951433 fail("insert(7, boolean) expected StringIndexOutOfBoundsException");
1196 } catch (IndexOutOfBoundsException e) {
1434 } catch (final IndexOutOfBoundsException e) {
11971435 // expected
11981436 }
11991437
12101448 try {
12111449 sb.insert(-1, '!');
12121450 fail("insert(-1, char) expected StringIndexOutOfBoundsException");
1213 } catch (IndexOutOfBoundsException e) {
1451 } catch (final IndexOutOfBoundsException e) {
12141452 // expected
12151453 }
12161454
12171455 try {
12181456 sb.insert(7, '!');
12191457 fail("insert(7, char) expected StringIndexOutOfBoundsException");
1220 } catch (IndexOutOfBoundsException e) {
1458 } catch (final IndexOutOfBoundsException e) {
12211459 // expected
12221460 }
12231461
12311469 try {
12321470 sb.insert(-1, 0);
12331471 fail("insert(-1, int) expected StringIndexOutOfBoundsException");
1234 } catch (IndexOutOfBoundsException e) {
1472 } catch (final IndexOutOfBoundsException e) {
12351473 // expected
12361474 }
12371475
12381476 try {
12391477 sb.insert(7, 0);
12401478 fail("insert(7, int) expected StringIndexOutOfBoundsException");
1241 } catch (IndexOutOfBoundsException e) {
1479 } catch (final IndexOutOfBoundsException e) {
12421480 // expected
12431481 }
12441482
12521490 try {
12531491 sb.insert(-1, 1L);
12541492 fail("insert(-1, long) expected StringIndexOutOfBoundsException");
1255 } catch (IndexOutOfBoundsException e) {
1493 } catch (final IndexOutOfBoundsException e) {
12561494 // expected
12571495 }
12581496
12591497 try {
12601498 sb.insert(7, 1L);
12611499 fail("insert(7, long) expected StringIndexOutOfBoundsException");
1262 } catch (IndexOutOfBoundsException e) {
1500 } catch (final IndexOutOfBoundsException e) {
12631501 // expected
12641502 }
12651503
12731511 try {
12741512 sb.insert(-1, 2.3F);
12751513 fail("insert(-1, float) expected StringIndexOutOfBoundsException");
1276 } catch (IndexOutOfBoundsException e) {
1514 } catch (final IndexOutOfBoundsException e) {
12771515 // expected
12781516 }
12791517
12801518 try {
12811519 sb.insert(7, 2.3F);
12821520 fail("insert(7, float) expected StringIndexOutOfBoundsException");
1283 } catch (IndexOutOfBoundsException e) {
1521 } catch (final IndexOutOfBoundsException e) {
12841522 // expected
12851523 }
12861524
12941532 try {
12951533 sb.insert(-1, 4.5D);
12961534 fail("insert(-1, double) expected StringIndexOutOfBoundsException");
1297 } catch (IndexOutOfBoundsException e) {
1535 } catch (final IndexOutOfBoundsException e) {
12981536 // expected
12991537 }
13001538
13011539 try {
13021540 sb.insert(7, 4.5D);
13031541 fail("insert(7, double) expected StringIndexOutOfBoundsException");
1304 } catch (IndexOutOfBoundsException e) {
1542 } catch (final IndexOutOfBoundsException e) {
13051543 // expected
13061544 }
13071545
13101548 }
13111549
13121550 //-----------------------------------------------------------------------
1551 @Test
13131552 public void testInsertWithNullText() {
1314 StrBuilder sb = new StrBuilder();
1553 final StrBuilder sb = new StrBuilder();
13151554 sb.setNullText("null");
13161555 sb.append("barbaz");
13171556 assertEquals("barbaz", sb.toString());
13191558 try {
13201559 sb.insert(-1, FOO);
13211560 fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
1322 } catch (IndexOutOfBoundsException e) {
1561 } catch (final IndexOutOfBoundsException e) {
13231562 // expected
13241563 }
13251564
13261565 try {
13271566 sb.insert(7, FOO);
13281567 fail("insert(7, Object) expected StringIndexOutOfBoundsException");
1329 } catch (IndexOutOfBoundsException e) {
1568 } catch (final IndexOutOfBoundsException e) {
13301569 // expected
13311570 }
13321571
13431582 try {
13441583 sb.insert(-1, "foo");
13451584 fail("insert(-1, String) expected StringIndexOutOfBoundsException");
1346 } catch (IndexOutOfBoundsException e) {
1585 } catch (final IndexOutOfBoundsException e) {
13471586 // expected
13481587 }
13491588
13501589 try {
13511590 sb.insert(7, "foo");
13521591 fail("insert(7, String) expected StringIndexOutOfBoundsException");
1353 } catch (IndexOutOfBoundsException e) {
1592 } catch (final IndexOutOfBoundsException e) {
13541593 // expected
13551594 }
13561595
1616
1717 package org.apache.commons.lang3.text;
1818
19 import org.junit.Test;
20 import static org.junit.Assert.*;
1921 import java.io.Reader;
2022 import java.io.Writer;
2123 import java.util.Arrays;
2224
23 import junit.framework.TestCase;
24
2525 import org.apache.commons.lang3.ArrayUtils;
2626
2727 /**
2828 * Unit tests for {@link org.apache.commons.lang3.text.StrBuilder}.
2929 *
30 * @version $Id: StrBuilderTest.java 1153484 2011-08-03 13:39:42Z ggregory $
30 * @version $Id: StrBuilderTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3131 */
32 public class StrBuilderTest extends TestCase {
33
34 /**
35 * Create a new test case with the specified name.
36 *
37 * @param name
38 * name
39 */
40 public StrBuilderTest(String name) {
41 super(name);
42 }
43
44 //-----------------------------------------------------------------------
32 public class StrBuilderTest {
33
34 //-----------------------------------------------------------------------
35 @Test
4536 public void testConstructors() {
46 StrBuilder sb0 = new StrBuilder();
37 final StrBuilder sb0 = new StrBuilder();
4738 assertEquals(32, sb0.capacity());
4839 assertEquals(0, sb0.length());
4940 assertEquals(0, sb0.size());
5041
51 StrBuilder sb1 = new StrBuilder(32);
42 final StrBuilder sb1 = new StrBuilder(32);
5243 assertEquals(32, sb1.capacity());
5344 assertEquals(0, sb1.length());
5445 assertEquals(0, sb1.size());
5546
56 StrBuilder sb2 = new StrBuilder(0);
47 final StrBuilder sb2 = new StrBuilder(0);
5748 assertEquals(32, sb2.capacity());
5849 assertEquals(0, sb2.length());
5950 assertEquals(0, sb2.size());
6051
61 StrBuilder sb3 = new StrBuilder(-1);
52 final StrBuilder sb3 = new StrBuilder(-1);
6253 assertEquals(32, sb3.capacity());
6354 assertEquals(0, sb3.length());
6455 assertEquals(0, sb3.size());
6556
66 StrBuilder sb4 = new StrBuilder(1);
57 final StrBuilder sb4 = new StrBuilder(1);
6758 assertEquals(1, sb4.capacity());
6859 assertEquals(0, sb4.length());
6960 assertEquals(0, sb4.size());
7061
71 StrBuilder sb5 = new StrBuilder((String) null);
62 final StrBuilder sb5 = new StrBuilder((String) null);
7263 assertEquals(32, sb5.capacity());
7364 assertEquals(0, sb5.length());
7465 assertEquals(0, sb5.size());
7566
76 StrBuilder sb6 = new StrBuilder("");
67 final StrBuilder sb6 = new StrBuilder("");
7768 assertEquals(32, sb6.capacity());
7869 assertEquals(0, sb6.length());
7970 assertEquals(0, sb6.size());
8071
81 StrBuilder sb7 = new StrBuilder("foo");
72 final StrBuilder sb7 = new StrBuilder("foo");
8273 assertEquals(35, sb7.capacity());
8374 assertEquals(3, sb7.length());
8475 assertEquals(3, sb7.size());
8576 }
8677
8778 //-----------------------------------------------------------------------
79 @Test
8880 public void testChaining() {
89 StrBuilder sb = new StrBuilder();
81 final StrBuilder sb = new StrBuilder();
9082 assertSame(sb, sb.setNewLineText(null));
9183 assertSame(sb, sb.setNullText(null));
9284 assertSame(sb, sb.setLength(1));
9991 }
10092
10193 //-----------------------------------------------------------------------
94 @Test
10295 public void testGetSetNewLineText() {
103 StrBuilder sb = new StrBuilder();
96 final StrBuilder sb = new StrBuilder();
10497 assertEquals(null, sb.getNewLineText());
10598
10699 sb.setNewLineText("#");
114107 }
115108
116109 //-----------------------------------------------------------------------
110 @Test
117111 public void testGetSetNullText() {
118 StrBuilder sb = new StrBuilder();
112 final StrBuilder sb = new StrBuilder();
119113 assertEquals(null, sb.getNullText());
120114
121115 sb.setNullText("null");
132126 }
133127
134128 //-----------------------------------------------------------------------
129 @Test
135130 public void testCapacityAndLength() {
136 StrBuilder sb = new StrBuilder();
131 final StrBuilder sb = new StrBuilder();
137132 assertEquals(32, sb.capacity());
138133 assertEquals(0, sb.length());
139134 assertEquals(0, sb.size());
184179 try {
185180 sb.setLength(-1);
186181 fail("setLength(-1) expected StringIndexOutOfBoundsException");
187 } catch (IndexOutOfBoundsException e) {
182 } catch (final IndexOutOfBoundsException e) {
188183 // expected
189184 }
190185
216211 }
217212
218213 //-----------------------------------------------------------------------
214 @Test
219215 public void testLength() {
220 StrBuilder sb = new StrBuilder();
216 final StrBuilder sb = new StrBuilder();
221217 assertEquals(0, sb.length());
222218
223219 sb.append("Hello");
224220 assertEquals(5, sb.length());
225221 }
226222
223 @Test
227224 public void testSetLength() {
228 StrBuilder sb = new StrBuilder();
225 final StrBuilder sb = new StrBuilder();
229226 sb.append("Hello");
230227 sb.setLength(2); // shorten
231228 assertEquals("He", sb.toString());
237234 try {
238235 sb.setLength(-1);
239236 fail("setLength(-1) expected StringIndexOutOfBoundsException");
240 } catch (IndexOutOfBoundsException e) {
237 } catch (final IndexOutOfBoundsException e) {
241238 // expected
242239 }
243240 }
244241
245242 //-----------------------------------------------------------------------
243 @Test
246244 public void testCapacity() {
247 StrBuilder sb = new StrBuilder();
245 final StrBuilder sb = new StrBuilder();
248246 assertEquals(sb.buffer.length, sb.capacity());
249247
250248 sb.append("HelloWorldHelloWorldHelloWorldHelloWorld");
251249 assertEquals(sb.buffer.length, sb.capacity());
252250 }
253251
252 @Test
254253 public void testEnsureCapacity() {
255 StrBuilder sb = new StrBuilder();
254 final StrBuilder sb = new StrBuilder();
256255 sb.ensureCapacity(2);
257 assertEquals(true, sb.capacity() >= 2);
256 assertTrue(sb.capacity() >= 2);
258257
259258 sb.ensureCapacity(-1);
260 assertEquals(true, sb.capacity() >= 0);
259 assertTrue(sb.capacity() >= 0);
261260
262261 sb.append("HelloWorld");
263262 sb.ensureCapacity(40);
264 assertEquals(true, sb.capacity() >= 40);
265 }
266
263 assertTrue(sb.capacity() >= 40);
264 }
265
266 @Test
267267 public void testMinimizeCapacity() {
268 StrBuilder sb = new StrBuilder();
268 final StrBuilder sb = new StrBuilder();
269269 sb.minimizeCapacity();
270270 assertEquals(0, sb.capacity());
271271
275275 }
276276
277277 //-----------------------------------------------------------------------
278 @Test
278279 public void testSize() {
279 StrBuilder sb = new StrBuilder();
280 final StrBuilder sb = new StrBuilder();
280281 assertEquals(0, sb.size());
281282
282283 sb.append("Hello");
283284 assertEquals(5, sb.size());
284285 }
285286
287 @Test
286288 public void testIsEmpty() {
287 StrBuilder sb = new StrBuilder();
288 assertEquals(true, sb.isEmpty());
289 final StrBuilder sb = new StrBuilder();
290 assertTrue(sb.isEmpty());
289291
290292 sb.append("Hello");
291 assertEquals(false, sb.isEmpty());
293 assertFalse(sb.isEmpty());
292294
293295 sb.clear();
294 assertEquals(true, sb.isEmpty());
295 }
296
296 assertTrue(sb.isEmpty());
297 }
298
299 @Test
297300 public void testClear() {
298 StrBuilder sb = new StrBuilder();
301 final StrBuilder sb = new StrBuilder();
299302 sb.append("Hello");
300303 sb.clear();
301304 assertEquals(0, sb.length());
302 assertEquals(true, sb.buffer.length >= 5);
303 }
304
305 //-----------------------------------------------------------------------
305 assertTrue(sb.buffer.length >= 5);
306 }
307
308 //-----------------------------------------------------------------------
309 @Test
306310 public void testCharAt() {
307 StrBuilder sb = new StrBuilder();
311 final StrBuilder sb = new StrBuilder();
308312 try {
309313 sb.charAt(0);
310314 fail("charAt(0) expected IndexOutOfBoundsException");
311 } catch (IndexOutOfBoundsException e) {
315 } catch (final IndexOutOfBoundsException e) {
312316 // expected
313317 }
314318 try {
315319 sb.charAt(-1);
316320 fail("charAt(-1) expected IndexOutOfBoundsException");
317 } catch (IndexOutOfBoundsException e) {
321 } catch (final IndexOutOfBoundsException e) {
318322 // expected
319323 }
320324 sb.append("foo");
324328 try {
325329 sb.charAt(-1);
326330 fail("charAt(-1) expected IndexOutOfBoundsException");
327 } catch (IndexOutOfBoundsException e) {
331 } catch (final IndexOutOfBoundsException e) {
328332 // expected
329333 }
330334 try {
331335 sb.charAt(3);
332336 fail("charAt(3) expected IndexOutOfBoundsException");
333 } catch (IndexOutOfBoundsException e) {
337 } catch (final IndexOutOfBoundsException e) {
334338 // expected
335339 }
336340 }
337341
338342 //-----------------------------------------------------------------------
343 @Test
339344 public void testSetCharAt() {
340 StrBuilder sb = new StrBuilder();
345 final StrBuilder sb = new StrBuilder();
341346 try {
342347 sb.setCharAt(0, 'f');
343348 fail("setCharAt(0,) expected IndexOutOfBoundsException");
344 } catch (IndexOutOfBoundsException e) {
349 } catch (final IndexOutOfBoundsException e) {
345350 // expected
346351 }
347352 try {
348353 sb.setCharAt(-1, 'f');
349354 fail("setCharAt(-1,) expected IndexOutOfBoundsException");
350 } catch (IndexOutOfBoundsException e) {
355 } catch (final IndexOutOfBoundsException e) {
351356 // expected
352357 }
353358 sb.append("foo");
357362 try {
358363 sb.setCharAt(3, '!');
359364 fail("setCharAt(3,) expected IndexOutOfBoundsException");
360 } catch (IndexOutOfBoundsException e) {
365 } catch (final IndexOutOfBoundsException e) {
361366 // expected
362367 }
363368 assertEquals("bar", sb.toString());
364369 }
365370
366371 //-----------------------------------------------------------------------
372 @Test
367373 public void testDeleteCharAt() {
368 StrBuilder sb = new StrBuilder("abc");
374 final StrBuilder sb = new StrBuilder("abc");
369375 sb.deleteCharAt(0);
370376 assertEquals("bc", sb.toString());
371377
372378 try {
373379 sb.deleteCharAt(1000);
374380 fail("Expected IndexOutOfBoundsException");
375 } catch (IndexOutOfBoundsException e) {}
376 }
377
378 //-----------------------------------------------------------------------
381 } catch (final IndexOutOfBoundsException e) {}
382 }
383
384 //-----------------------------------------------------------------------
385 @Test
379386 public void testToCharArray() {
380 StrBuilder sb = new StrBuilder();
387 final StrBuilder sb = new StrBuilder();
381388 assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, sb.toCharArray());
382389
383390 char[] a = sb.toCharArray();
390397 assertTrue("toCharArray() result does not match", Arrays.equals("junit".toCharArray(), a));
391398 }
392399
400 @Test
393401 public void testToCharArrayIntInt() {
394 StrBuilder sb = new StrBuilder();
402 final StrBuilder sb = new StrBuilder();
395403 assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, sb.toCharArray(0, 0));
396404
397405 sb.append("junit");
413421 try {
414422 sb.toCharArray(-1, 5);
415423 fail("no string index out of bound on -1");
416 } catch (IndexOutOfBoundsException e) {
424 } catch (final IndexOutOfBoundsException e) {
417425 }
418426
419427 try {
420428 sb.toCharArray(6, 5);
421429 fail("no string index out of bound on -1");
422 } catch (IndexOutOfBoundsException e) {
423 }
424 }
425
430 } catch (final IndexOutOfBoundsException e) {
431 }
432 }
433
434 @Test
426435 public void testGetChars ( ) {
427 StrBuilder sb = new StrBuilder();
436 final StrBuilder sb = new StrBuilder();
428437
429438 char[] input = new char[10];
430439 char[] a = sb.getChars(input);
450459 assertNotSame(input, a);
451460 }
452461
462 @Test
453463 public void testGetCharsIntIntCharArrayInt( ) {
454 StrBuilder sb = new StrBuilder();
464 final StrBuilder sb = new StrBuilder();
455465
456466 sb.append("junit");
457467 char[] a = new char[5];
466476 sb.getChars(-1,0,a,0);
467477 fail("no exception");
468478 }
469 catch (IndexOutOfBoundsException e) {
479 catch (final IndexOutOfBoundsException e) {
470480 }
471481
472482 try {
473483 sb.getChars(0,-1,a,0);
474484 fail("no exception");
475485 }
476 catch (IndexOutOfBoundsException e) {
486 catch (final IndexOutOfBoundsException e) {
477487 }
478488
479489 try {
480490 sb.getChars(0,20,a,0);
481491 fail("no exception");
482492 }
483 catch (IndexOutOfBoundsException e) {
493 catch (final IndexOutOfBoundsException e) {
484494 }
485495
486496 try {
487497 sb.getChars(4,2,a,0);
488498 fail("no exception");
489499 }
490 catch (IndexOutOfBoundsException e) {
491 }
492 }
493
494 //-----------------------------------------------------------------------
500 catch (final IndexOutOfBoundsException e) {
501 }
502 }
503
504 //-----------------------------------------------------------------------
505 @Test
495506 public void testDeleteIntInt() {
496507 StrBuilder sb = new StrBuilder("abc");
497508 sb.delete(0, 1);
506517 try {
507518 sb.delete(1, 2);
508519 fail("Expected IndexOutOfBoundsException");
509 } catch (IndexOutOfBoundsException e) {}
520 } catch (final IndexOutOfBoundsException e) {}
510521 try {
511522 sb.delete(-1, 1);
512523 fail("Expected IndexOutOfBoundsException");
513 } catch (IndexOutOfBoundsException e) {}
524 } catch (final IndexOutOfBoundsException e) {}
514525
515526 sb = new StrBuilder("anything");
516527 try {
517528 sb.delete(2, 1);
518529 fail("Expected IndexOutOfBoundsException");
519 } catch (IndexOutOfBoundsException e) {}
520 }
521
522 //-----------------------------------------------------------------------
530 } catch (final IndexOutOfBoundsException e) {}
531 }
532
533 //-----------------------------------------------------------------------
534 @Test
523535 public void testDeleteAll_char() {
524536 StrBuilder sb = new StrBuilder("abcbccba");
525537 sb.deleteAll('X');
536548 assertEquals("", sb.toString());
537549 }
538550
551 @Test
539552 public void testDeleteFirst_char() {
540553 StrBuilder sb = new StrBuilder("abcba");
541554 sb.deleteFirst('X');
553566 }
554567
555568 // -----------------------------------------------------------------------
569 @Test
556570 public void testDeleteAll_String() {
557571 StrBuilder sb = new StrBuilder("abcbccba");
558572 sb.deleteAll((String) null);
578592 assertEquals("", sb.toString());
579593 }
580594
595 @Test
581596 public void testDeleteFirst_String() {
582597 StrBuilder sb = new StrBuilder("abcbccba");
583598 sb.deleteFirst((String) null);
604619 }
605620
606621 // -----------------------------------------------------------------------
622 @Test
607623 public void testDeleteAll_StrMatcher() {
608624 StrBuilder sb = new StrBuilder("A0xA1A2yA3");
609625 sb.deleteAll((StrMatcher) null);
620636 assertEquals("", sb.toString());
621637 }
622638
639 @Test
623640 public void testDeleteFirst_StrMatcher() {
624641 StrBuilder sb = new StrBuilder("A0xA1A2yA3");
625642 sb.deleteFirst((StrMatcher) null);
637654 }
638655
639656 // -----------------------------------------------------------------------
657 @Test
640658 public void testReplace_int_int_String() {
641659 StrBuilder sb = new StrBuilder("abc");
642660 sb.replace(0, 1, "d");
658676 try {
659677 sb.replace(2, 1, "anything");
660678 fail("Expected IndexOutOfBoundsException");
661 } catch (IndexOutOfBoundsException e) {}
679 } catch (final IndexOutOfBoundsException e) {}
662680
663681 sb = new StrBuilder();
664682 try {
665683 sb.replace(1, 2, "anything");
666684 fail("Expected IndexOutOfBoundsException");
667 } catch (IndexOutOfBoundsException e) {}
685 } catch (final IndexOutOfBoundsException e) {}
668686 try {
669687 sb.replace(-1, 1, "anything");
670688 fail("Expected IndexOutOfBoundsException");
671 } catch (IndexOutOfBoundsException e) {}
672 }
673
674 //-----------------------------------------------------------------------
689 } catch (final IndexOutOfBoundsException e) {}
690 }
691
692 //-----------------------------------------------------------------------
693 @Test
675694 public void testReplaceAll_char_char() {
676 StrBuilder sb = new StrBuilder("abcbccba");
695 final StrBuilder sb = new StrBuilder("abcbccba");
677696 sb.replaceAll('x', 'y');
678697 assertEquals("abcbccba", sb.toString());
679698 sb.replaceAll('a', 'd');
687706 }
688707
689708 //-----------------------------------------------------------------------
709 @Test
690710 public void testReplaceFirst_char_char() {
691 StrBuilder sb = new StrBuilder("abcbccba");
711 final StrBuilder sb = new StrBuilder("abcbccba");
692712 sb.replaceFirst('x', 'y');
693713 assertEquals("abcbccba", sb.toString());
694714 sb.replaceFirst('a', 'd');
702722 }
703723
704724 //-----------------------------------------------------------------------
725 @Test
705726 public void testReplaceAll_String_String() {
706727 StrBuilder sb = new StrBuilder("abcbccba");
707728 sb.replaceAll((String) null, null);
731752 assertEquals("xbxxbx", sb.toString());
732753 }
733754
755 @Test
734756 public void testReplaceFirst_String_String() {
735757 StrBuilder sb = new StrBuilder("abcbccba");
736758 sb.replaceFirst((String) null, null);
761783 }
762784
763785 //-----------------------------------------------------------------------
786 @Test
764787 public void testReplaceAll_StrMatcher_String() {
765788 StrBuilder sb = new StrBuilder("abcbccba");
766789 sb.replaceAll((StrMatcher) null, null);
794817 assertEquals("***-******-***", sb.toString());
795818 }
796819
820 @Test
797821 public void testReplaceFirst_StrMatcher_String() {
798822 StrBuilder sb = new StrBuilder("abcbccba");
799823 sb.replaceFirst((StrMatcher) null, null);
828852 }
829853
830854 //-----------------------------------------------------------------------
855 @Test
831856 public void testReplace_StrMatcher_String_int_int_int_VaryMatcher() {
832857 StrBuilder sb = new StrBuilder("abcbccba");
833858 sb.replace((StrMatcher) null, "x", 0, sb.length(), -1);
848873 assertEquals("", sb.toString());
849874 }
850875
876 @Test
851877 public void testReplace_StrMatcher_String_int_int_int_VaryReplace() {
852878 StrBuilder sb = new StrBuilder("abcbccba");
853879 sb.replace(StrMatcher.stringMatcher("cb"), "cb", 0, sb.length(), -1);
870896 assertEquals("abca", sb.toString());
871897 }
872898
899 @Test
873900 public void testReplace_StrMatcher_String_int_int_int_VaryStartIndex() {
874901 StrBuilder sb = new StrBuilder("aaxaaaayaa");
875902 sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, sb.length(), -1);
919946 try {
920947 sb.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb.length(), -1);
921948 fail();
922 } catch (IndexOutOfBoundsException ex) {}
949 } catch (final IndexOutOfBoundsException ex) {}
923950 assertEquals("aaxaaaayaa", sb.toString());
924951
925952 sb = new StrBuilder("aaxaaaayaa");
926953 try {
927954 sb.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb.length(), -1);
928955 fail();
929 } catch (IndexOutOfBoundsException ex) {}
956 } catch (final IndexOutOfBoundsException ex) {}
930957 assertEquals("aaxaaaayaa", sb.toString());
931958 }
932959
960 @Test
933961 public void testReplace_StrMatcher_String_int_int_int_VaryEndIndex() {
934962 StrBuilder sb = new StrBuilder("aaxaaaayaa");
935963 sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 0, -1);
9791007 try {
9801008 sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1);
9811009 fail();
982 } catch (IndexOutOfBoundsException ex) {}
1010 } catch (final IndexOutOfBoundsException ex) {}
9831011 assertEquals("aaxaaaayaa", sb.toString());
9841012 }
9851013
1014 @Test
9861015 public void testReplace_StrMatcher_String_int_int_int_VaryCount() {
9871016 StrBuilder sb = new StrBuilder("aaxaaaayaa");
9881017 sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, -1);
10141043 }
10151044
10161045 //-----------------------------------------------------------------------
1046 @Test
10171047 public void testReverse() {
1018 StrBuilder sb = new StrBuilder();
1048 final StrBuilder sb = new StrBuilder();
10191049 assertEquals("", sb.reverse().toString());
10201050
10211051 sb.clear().append(true);
10241054 }
10251055
10261056 //-----------------------------------------------------------------------
1057 @Test
10271058 public void testTrim() {
1028 StrBuilder sb = new StrBuilder();
1059 final StrBuilder sb = new StrBuilder();
10291060 assertEquals("", sb.reverse().toString());
10301061
10311062 sb.clear().append(" \u0000 ");
10451076 }
10461077
10471078 //-----------------------------------------------------------------------
1079 @Test
10481080 public void testStartsWith() {
1049 StrBuilder sb = new StrBuilder();
1081 final StrBuilder sb = new StrBuilder();
10501082 assertFalse(sb.startsWith("a"));
10511083 assertFalse(sb.startsWith(null));
10521084 assertTrue(sb.startsWith(""));
10571089 assertFalse(sb.startsWith("cba"));
10581090 }
10591091
1092 @Test
10601093 public void testEndsWith() {
1061 StrBuilder sb = new StrBuilder();
1094 final StrBuilder sb = new StrBuilder();
10621095 assertFalse(sb.endsWith("a"));
10631096 assertFalse(sb.endsWith("c"));
10641097 assertTrue(sb.endsWith(""));
10741107 }
10751108
10761109 //-----------------------------------------------------------------------
1110 @Test
10771111 public void testSubSequenceIntInt() {
1078 StrBuilder sb = new StrBuilder ("hello goodbye");
1112 final StrBuilder sb = new StrBuilder ("hello goodbye");
10791113 // Start index is negative
10801114 try {
10811115 sb.subSequence(-1, 5);
10821116 fail();
1083 } catch (IndexOutOfBoundsException e) {}
1117 } catch (final IndexOutOfBoundsException e) {}
10841118
10851119 // End index is negative
10861120 try {
10871121 sb.subSequence(2, -1);
10881122 fail();
1089 } catch (IndexOutOfBoundsException e) {}
1123 } catch (final IndexOutOfBoundsException e) {}
10901124
10911125 // End index greater than length()
10921126 try {
10931127 sb.subSequence(2, sb.length() + 1);
10941128 fail();
1095 } catch (IndexOutOfBoundsException e) {}
1129 } catch (final IndexOutOfBoundsException e) {}
10961130
10971131 // Start index greater then end index
10981132 try {
10991133 sb.subSequence(3, 2);
11001134 fail();
1101 } catch (IndexOutOfBoundsException e) {}
1135 } catch (final IndexOutOfBoundsException e) {}
11021136
11031137 // Normal cases
11041138 assertEquals ("hello", sb.subSequence(0, 5));
11071141 assertEquals ("hello goodbye".subSequence(6,13), sb.subSequence(6, 13));
11081142 }
11091143
1144 @Test
11101145 public void testSubstringInt() {
1111 StrBuilder sb = new StrBuilder ("hello goodbye");
1146 final StrBuilder sb = new StrBuilder ("hello goodbye");
11121147 assertEquals ("goodbye", sb.substring(6));
11131148 assertEquals ("hello goodbye".substring(6), sb.substring(6));
11141149 assertEquals ("hello goodbye", sb.substring(0));
11161151 try {
11171152 sb.substring(-1);
11181153 fail ();
1119 } catch (IndexOutOfBoundsException e) {}
1154 } catch (final IndexOutOfBoundsException e) {}
11201155
11211156 try {
11221157 sb.substring(15);
11231158 fail ();
1124 } catch (IndexOutOfBoundsException e) {}
1159 } catch (final IndexOutOfBoundsException e) {}
11251160
11261161 }
11271162
1163 @Test
11281164 public void testSubstringIntInt() {
1129 StrBuilder sb = new StrBuilder ("hello goodbye");
1165 final StrBuilder sb = new StrBuilder ("hello goodbye");
11301166 assertEquals ("hello", sb.substring(0, 5));
11311167 assertEquals ("hello goodbye".substring(0, 6), sb.substring(0, 6));
11321168
11381174 try {
11391175 sb.substring(-1, 5);
11401176 fail();
1141 } catch (IndexOutOfBoundsException e) {}
1177 } catch (final IndexOutOfBoundsException e) {}
11421178
11431179 try {
11441180 sb.substring(15, 20);
11451181 fail();
1146 } catch (IndexOutOfBoundsException e) {}
1182 } catch (final IndexOutOfBoundsException e) {}
11471183 }
11481184
11491185 // -----------------------------------------------------------------------
1186 @Test
11501187 public void testMidString() {
1151 StrBuilder sb = new StrBuilder("hello goodbye hello");
1188 final StrBuilder sb = new StrBuilder("hello goodbye hello");
11521189 assertEquals("goodbye", sb.midString(6, 7));
11531190 assertEquals("hello", sb.midString(0, 5));
11541191 assertEquals("hello", sb.midString(-5, 5));
11571194 assertEquals("hello", sb.midString(14, 22));
11581195 }
11591196
1197 @Test
11601198 public void testRightString() {
1161 StrBuilder sb = new StrBuilder("left right");
1199 final StrBuilder sb = new StrBuilder("left right");
11621200 assertEquals("right", sb.rightString(5));
11631201 assertEquals("", sb.rightString(0));
11641202 assertEquals("", sb.rightString(-5));
11651203 assertEquals("left right", sb.rightString(15));
11661204 }
11671205
1206 @Test
11681207 public void testLeftString() {
1169 StrBuilder sb = new StrBuilder("left right");
1208 final StrBuilder sb = new StrBuilder("left right");
11701209 assertEquals("left", sb.leftString(4));
11711210 assertEquals("", sb.leftString(0));
11721211 assertEquals("", sb.leftString(-5));
11741213 }
11751214
11761215 // -----------------------------------------------------------------------
1216 @Test
11771217 public void testContains_char() {
1178 StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
1179 assertEquals(true, sb.contains('a'));
1180 assertEquals(true, sb.contains('o'));
1181 assertEquals(true, sb.contains('z'));
1182 assertEquals(false, sb.contains('1'));
1183 }
1184
1218 final StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
1219 assertTrue(sb.contains('a'));
1220 assertTrue(sb.contains('o'));
1221 assertTrue(sb.contains('z'));
1222 assertFalse(sb.contains('1'));
1223 }
1224
1225 @Test
11851226 public void testContains_String() {
1186 StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
1187 assertEquals(true, sb.contains("a"));
1188 assertEquals(true, sb.contains("pq"));
1189 assertEquals(true, sb.contains("z"));
1190 assertEquals(false, sb.contains("zyx"));
1191 assertEquals(false, sb.contains((String) null));
1192 }
1193
1227 final StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
1228 assertTrue(sb.contains("a"));
1229 assertTrue(sb.contains("pq"));
1230 assertTrue(sb.contains("z"));
1231 assertFalse(sb.contains("zyx"));
1232 assertFalse(sb.contains((String) null));
1233 }
1234
1235 @Test
11941236 public void testContains_StrMatcher() {
11951237 StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
1196 assertEquals(true, sb.contains(StrMatcher.charMatcher('a')));
1197 assertEquals(true, sb.contains(StrMatcher.stringMatcher("pq")));
1198 assertEquals(true, sb.contains(StrMatcher.charMatcher('z')));
1199 assertEquals(false, sb.contains(StrMatcher.stringMatcher("zy")));
1200 assertEquals(false, sb.contains((StrMatcher) null));
1238 assertTrue(sb.contains(StrMatcher.charMatcher('a')));
1239 assertTrue(sb.contains(StrMatcher.stringMatcher("pq")));
1240 assertTrue(sb.contains(StrMatcher.charMatcher('z')));
1241 assertFalse(sb.contains(StrMatcher.stringMatcher("zy")));
1242 assertFalse(sb.contains((StrMatcher) null));
12011243
12021244 sb = new StrBuilder();
1203 assertEquals(false, sb.contains(A_NUMBER_MATCHER));
1245 assertFalse(sb.contains(A_NUMBER_MATCHER));
12041246 sb.append("B A1 C");
1205 assertEquals(true, sb.contains(A_NUMBER_MATCHER));
1247 assertTrue(sb.contains(A_NUMBER_MATCHER));
12061248 }
12071249
12081250 // -----------------------------------------------------------------------
1251 @Test
12091252 public void testIndexOf_char() {
1210 StrBuilder sb = new StrBuilder("abab");
1253 final StrBuilder sb = new StrBuilder("abab");
12111254 assertEquals(0, sb.indexOf('a'));
12121255
12131256 // should work like String#indexOf
12191262 assertEquals(-1, sb.indexOf('z'));
12201263 }
12211264
1265 @Test
12221266 public void testIndexOf_char_int() {
12231267 StrBuilder sb = new StrBuilder("abab");
12241268 assertEquals(0, sb.indexOf('a', -1));
12401284 assertEquals(-1, sb.indexOf('z', 3));
12411285 }
12421286
1287 @Test
12431288 public void testLastIndexOf_char() {
1244 StrBuilder sb = new StrBuilder("abab");
1289 final StrBuilder sb = new StrBuilder("abab");
12451290
12461291 assertEquals (2, sb.lastIndexOf('a'));
12471292 //should work like String#lastIndexOf
12531298 assertEquals (-1, sb.lastIndexOf('z'));
12541299 }
12551300
1301 @Test
12561302 public void testLastIndexOf_char_int() {
12571303 StrBuilder sb = new StrBuilder("abab");
12581304 assertEquals(-1, sb.lastIndexOf('a', -1));
12731319 }
12741320
12751321 // -----------------------------------------------------------------------
1322 @Test
12761323 public void testIndexOf_String() {
1277 StrBuilder sb = new StrBuilder("abab");
1324 final StrBuilder sb = new StrBuilder("abab");
12781325
12791326 assertEquals(0, sb.indexOf("a"));
12801327 //should work like String#indexOf
12951342 assertEquals(-1, sb.indexOf((String) null));
12961343 }
12971344
1345 @Test
12981346 public void testIndexOf_String_int() {
12991347 StrBuilder sb = new StrBuilder("abab");
13001348 assertEquals(0, sb.indexOf("a", -1));
13311379 assertEquals(-1, sb.indexOf((String) null, 2));
13321380 }
13331381
1382 @Test
13341383 public void testLastIndexOf_String() {
1335 StrBuilder sb = new StrBuilder("abab");
1384 final StrBuilder sb = new StrBuilder("abab");
13361385
13371386 assertEquals(2, sb.lastIndexOf("a"));
13381387 //should work like String#lastIndexOf
13531402 assertEquals(-1, sb.lastIndexOf((String) null));
13541403 }
13551404
1405 @Test
13561406 public void testLastIndexOf_String_int() {
13571407 StrBuilder sb = new StrBuilder("abab");
13581408 assertEquals(-1, sb.lastIndexOf("a", -1));
13901440 }
13911441
13921442 // -----------------------------------------------------------------------
1443 @Test
13931444 public void testIndexOf_StrMatcher() {
1394 StrBuilder sb = new StrBuilder();
1445 final StrBuilder sb = new StrBuilder();
13951446 assertEquals(-1, sb.indexOf((StrMatcher) null));
13961447 assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a')));
13971448
14071458 assertEquals(6, sb.indexOf(A_NUMBER_MATCHER));
14081459 }
14091460
1461 @Test
14101462 public void testIndexOf_StrMatcher_int() {
1411 StrBuilder sb = new StrBuilder();
1463 final StrBuilder sb = new StrBuilder();
14121464 assertEquals(-1, sb.indexOf((StrMatcher) null, 2));
14131465 assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 2));
14141466 assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 0));
14461498 assertEquals(-1, sb.indexOf(A_NUMBER_MATCHER, 24));
14471499 }
14481500
1501 @Test
14491502 public void testLastIndexOf_StrMatcher() {
1450 StrBuilder sb = new StrBuilder();
1503 final StrBuilder sb = new StrBuilder();
14511504 assertEquals(-1, sb.lastIndexOf((StrMatcher) null));
14521505 assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a')));
14531506
14631516 assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER));
14641517 }
14651518
1519 @Test
14661520 public void testLastIndexOf_StrMatcher_int() {
1467 StrBuilder sb = new StrBuilder();
1521 final StrBuilder sb = new StrBuilder();
14681522 assertEquals(-1, sb.lastIndexOf((StrMatcher) null, 2));
14691523 assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 2));
14701524 assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 0));
15051559
15061560 static final StrMatcher A_NUMBER_MATCHER = new StrMatcher() {
15071561 @Override
1508 public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
1562 public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
15091563 if (buffer[pos] == 'A') {
15101564 pos++;
15111565 if (pos < bufferEnd && buffer[pos] >= '0' && buffer[pos] <= '9') {
15171571 };
15181572
15191573 //-----------------------------------------------------------------------
1574 @Test
15201575 public void testAsTokenizer() throws Exception {
15211576 // from Javadoc
1522 StrBuilder b = new StrBuilder();
1577 final StrBuilder b = new StrBuilder();
15231578 b.append("a b ");
1524 StrTokenizer t = b.asTokenizer();
1525
1526 String[] tokens1 = t.getTokenArray();
1579 final StrTokenizer t = b.asTokenizer();
1580
1581 final String[] tokens1 = t.getTokenArray();
15271582 assertEquals(2, tokens1.length);
15281583 assertEquals("a", tokens1[0]);
15291584 assertEquals("b", tokens1[1]);
15301585 assertEquals(2, t.size());
15311586
15321587 b.append("c d ");
1533 String[] tokens2 = t.getTokenArray();
1588 final String[] tokens2 = t.getTokenArray();
15341589 assertEquals(2, tokens2.length);
15351590 assertEquals("a", tokens2[0]);
15361591 assertEquals("b", tokens2[1]);
15391594 assertEquals("b", t.next());
15401595
15411596 t.reset();
1542 String[] tokens3 = t.getTokenArray();
1597 final String[] tokens3 = t.getTokenArray();
15431598 assertEquals(4, tokens3.length);
15441599 assertEquals("a", tokens3[0]);
15451600 assertEquals("b", tokens3[1]);
15551610 }
15561611
15571612 // -----------------------------------------------------------------------
1613 @Test
15581614 public void testAsReader() throws Exception {
1559 StrBuilder sb = new StrBuilder("some text");
1615 final StrBuilder sb = new StrBuilder("some text");
15601616 Reader reader = sb.asReader();
1561 assertEquals(true, reader.ready());
1562 char[] buf = new char[40];
1617 assertTrue(reader.ready());
1618 final char[] buf = new char[40];
15631619 assertEquals(9, reader.read(buf));
15641620 assertEquals("some text", new String(buf, 0, 9));
15651621
15661622 assertEquals(-1, reader.read());
1567 assertEquals(false, reader.ready());
1623 assertFalse(reader.ready());
15681624 assertEquals(0, reader.skip(2));
15691625 assertEquals(0, reader.skip(-1));
15701626
1571 assertEquals(true, reader.markSupported());
1627 assertTrue(reader.markSupported());
15721628 reader = sb.asReader();
15731629 assertEquals('s', reader.read());
15741630 reader.mark(-1);
15851641 assertEquals(2, reader.skip(2));
15861642 assertEquals(' ', reader.read());
15871643
1588 assertEquals(true, reader.ready());
1644 assertTrue(reader.ready());
15891645 reader.close();
1590 assertEquals(true, reader.ready());
1646 assertTrue(reader.ready());
15911647
15921648 reader = sb.asReader();
15931649 array = new char[3];
15941650 try {
15951651 reader.read(array, -1, 0);
15961652 fail();
1597 } catch (IndexOutOfBoundsException ex) {}
1653 } catch (final IndexOutOfBoundsException ex) {}
15981654 try {
15991655 reader.read(array, 0, -1);
16001656 fail();
1601 } catch (IndexOutOfBoundsException ex) {}
1657 } catch (final IndexOutOfBoundsException ex) {}
16021658 try {
16031659 reader.read(array, 100, 1);
16041660 fail();
1605 } catch (IndexOutOfBoundsException ex) {}
1661 } catch (final IndexOutOfBoundsException ex) {}
16061662 try {
16071663 reader.read(array, 0, 100);
16081664 fail();
1609 } catch (IndexOutOfBoundsException ex) {}
1665 } catch (final IndexOutOfBoundsException ex) {}
16101666 try {
16111667 reader.read(array, Integer.MAX_VALUE, Integer.MAX_VALUE);
16121668 fail();
1613 } catch (IndexOutOfBoundsException ex) {}
1669 } catch (final IndexOutOfBoundsException ex) {}
16141670
16151671 assertEquals(0, reader.read(array, 0, 0));
16161672 assertEquals(0, array[0]);
16261682 }
16271683
16281684 //-----------------------------------------------------------------------
1685 @Test
16291686 public void testAsWriter() throws Exception {
1630 StrBuilder sb = new StrBuilder("base");
1631 Writer writer = sb.asWriter();
1687 final StrBuilder sb = new StrBuilder("base");
1688 final Writer writer = sb.asWriter();
16321689
16331690 writer.write('l');
16341691 assertEquals("basel", sb.toString());
16601717 }
16611718
16621719 //-----------------------------------------------------------------------
1720 @Test
16631721 public void testEqualsIgnoreCase() {
1664 StrBuilder sb1 = new StrBuilder();
1665 StrBuilder sb2 = new StrBuilder();
1666 assertEquals(true, sb1.equalsIgnoreCase(sb1));
1667 assertEquals(true, sb1.equalsIgnoreCase(sb2));
1668 assertEquals(true, sb2.equalsIgnoreCase(sb2));
1722 final StrBuilder sb1 = new StrBuilder();
1723 final StrBuilder sb2 = new StrBuilder();
1724 assertTrue(sb1.equalsIgnoreCase(sb1));
1725 assertTrue(sb1.equalsIgnoreCase(sb2));
1726 assertTrue(sb2.equalsIgnoreCase(sb2));
16691727
16701728 sb1.append("abc");
1671 assertEquals(false, sb1.equalsIgnoreCase(sb2));
1729 assertFalse(sb1.equalsIgnoreCase(sb2));
16721730
16731731 sb2.append("ABC");
1674 assertEquals(true, sb1.equalsIgnoreCase(sb2));
1732 assertTrue(sb1.equalsIgnoreCase(sb2));
16751733
16761734 sb2.clear().append("abc");
1677 assertEquals(true, sb1.equalsIgnoreCase(sb2));
1678 assertEquals(true, sb1.equalsIgnoreCase(sb1));
1679 assertEquals(true, sb2.equalsIgnoreCase(sb2));
1735 assertTrue(sb1.equalsIgnoreCase(sb2));
1736 assertTrue(sb1.equalsIgnoreCase(sb1));
1737 assertTrue(sb2.equalsIgnoreCase(sb2));
16801738
16811739 sb2.clear().append("aBc");
1682 assertEquals(true, sb1.equalsIgnoreCase(sb2));
1683 }
1684
1685 //-----------------------------------------------------------------------
1740 assertTrue(sb1.equalsIgnoreCase(sb2));
1741 }
1742
1743 //-----------------------------------------------------------------------
1744 @Test
16861745 public void testEquals() {
1687 StrBuilder sb1 = new StrBuilder();
1688 StrBuilder sb2 = new StrBuilder();
1689 assertEquals(true, sb1.equals(sb2));
1690 assertEquals(true, sb1.equals(sb1));
1691 assertEquals(true, sb2.equals(sb2));
1692 assertEquals(true, sb1.equals((Object) sb2));
1746 final StrBuilder sb1 = new StrBuilder();
1747 final StrBuilder sb2 = new StrBuilder();
1748 assertTrue(sb1.equals(sb2));
1749 assertTrue(sb1.equals(sb1));
1750 assertTrue(sb2.equals(sb2));
1751 assertTrue(sb1.equals((Object) sb2));
16931752
16941753 sb1.append("abc");
1695 assertEquals(false, sb1.equals(sb2));
1696 assertEquals(false, sb1.equals((Object) sb2));
1754 assertFalse(sb1.equals(sb2));
1755 assertFalse(sb1.equals((Object) sb2));
16971756
16981757 sb2.append("ABC");
1699 assertEquals(false, sb1.equals(sb2));
1700 assertEquals(false, sb1.equals((Object) sb2));
1758 assertFalse(sb1.equals(sb2));
1759 assertFalse(sb1.equals((Object) sb2));
17011760
17021761 sb2.clear().append("abc");
1703 assertEquals(true, sb1.equals(sb2));
1704 assertEquals(true, sb1.equals((Object) sb2));
1705
1706 assertEquals(false, sb1.equals(Integer.valueOf(1)));
1707 assertEquals(false, sb1.equals("abc"));
1708 }
1709
1710 //-----------------------------------------------------------------------
1762 assertTrue(sb1.equals(sb2));
1763 assertTrue(sb1.equals((Object) sb2));
1764
1765 assertFalse(sb1.equals(Integer.valueOf(1)));
1766 assertFalse(sb1.equals("abc"));
1767 }
1768
1769 //-----------------------------------------------------------------------
1770 @Test
17111771 public void testHashCode() {
1712 StrBuilder sb = new StrBuilder();
1713 int hc1a = sb.hashCode();
1714 int hc1b = sb.hashCode();
1772 final StrBuilder sb = new StrBuilder();
1773 final int hc1a = sb.hashCode();
1774 final int hc1b = sb.hashCode();
17151775 assertEquals(0, hc1a);
17161776 assertEquals(hc1a, hc1b);
17171777
17181778 sb.append("abc");
1719 int hc2a = sb.hashCode();
1720 int hc2b = sb.hashCode();
1721 assertEquals(true, hc2a != 0);
1779 final int hc2a = sb.hashCode();
1780 final int hc2b = sb.hashCode();
1781 assertTrue(hc2a != 0);
17221782 assertEquals(hc2a, hc2b);
17231783 }
17241784
17251785 //-----------------------------------------------------------------------
1786 @Test
17261787 public void testToString() {
1727 StrBuilder sb = new StrBuilder("abc");
1788 final StrBuilder sb = new StrBuilder("abc");
17281789 assertEquals("abc", sb.toString());
17291790 }
17301791
17311792 //-----------------------------------------------------------------------
1793 @Test
17321794 public void testToStringBuffer() {
1733 StrBuilder sb = new StrBuilder();
1795 final StrBuilder sb = new StrBuilder();
17341796 assertEquals(new StringBuffer().toString(), sb.toStringBuffer().toString());
17351797
17361798 sb.append("junit");
17381800 }
17391801
17401802 //-----------------------------------------------------------------------
1803 @Test
1804 public void testToStringBuilder() {
1805 final StrBuilder sb = new StrBuilder();
1806 assertEquals(new StringBuilder().toString(), sb.toStringBuilder().toString());
1807
1808 sb.append("junit");
1809 assertEquals(new StringBuilder("junit").toString(), sb.toStringBuilder().toString());
1810 }
1811
1812 //-----------------------------------------------------------------------
1813 @Test
17411814 public void testLang294() {
1742 StrBuilder sb = new StrBuilder("\n%BLAH%\nDo more stuff\neven more stuff\n%BLAH%\n");
1815 final StrBuilder sb = new StrBuilder("\n%BLAH%\nDo more stuff\neven more stuff\n%BLAH%\n");
17431816 sb.deleteAll("\n%BLAH%");
17441817 assertEquals("\nDo more stuff\neven more stuff\n", sb.toString());
17451818 }
17461819
1820 @Test
17471821 public void testIndexOfLang294() {
1748 StrBuilder sb = new StrBuilder("onetwothree");
1822 final StrBuilder sb = new StrBuilder("onetwothree");
17491823 sb.deleteFirst("three");
17501824 assertEquals(-1, sb.indexOf("three"));
17511825 }
17521826
17531827 //-----------------------------------------------------------------------
1828 @Test
17541829 public void testLang295() {
1755 StrBuilder sb = new StrBuilder("onetwothree");
1830 final StrBuilder sb = new StrBuilder("onetwothree");
17561831 sb.deleteFirst("three");
17571832 assertFalse( "The contains(char) method is looking beyond the end of the string", sb.contains('h'));
17581833 assertEquals( "The indexOf(char) method is looking beyond the end of the string", -1, sb.indexOf('h'));
17591834 }
17601835
17611836 //-----------------------------------------------------------------------
1837 @Test
17621838 public void testLang412Right() {
1763 StrBuilder sb = new StrBuilder();
1839 final StrBuilder sb = new StrBuilder();
17641840 sb.appendFixedWidthPadRight(null, 10, '*');
17651841 assertEquals( "Failed to invoke appendFixedWidthPadRight correctly", "**********", sb.toString());
17661842 }
17671843
1844 @Test
17681845 public void testLang412Left() {
1769 StrBuilder sb = new StrBuilder();
1846 final StrBuilder sb = new StrBuilder();
17701847 sb.appendFixedWidthPadLeft(null, 10, '*');
17711848 assertEquals( "Failed to invoke appendFixedWidthPadLeft correctly", "**********", sb.toString());
17721849 }
17731850
1851 @Test
1852 public void testAsBuilder() {
1853 final StrBuilder sb = new StrBuilder().appendAll("Lorem", " ", "ipsum", " ", "dolor");
1854 assertEquals(sb.toString(), sb.build());
1855 }
1856
17741857 }
1616
1717 package org.apache.commons.lang3.text;
1818
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.fail;
21
1922 import java.util.HashMap;
2023 import java.util.Map;
2124
22 import junit.framework.TestCase;
25 import org.junit.Test;
2326
2427 /**
2528 * Test class for StrLookup.
2629 *
27 * @version $Id: StrLookupTest.java 1153484 2011-08-03 13:39:42Z ggregory $
30 * @version $Id: StrLookupTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2831 */
29 public class StrLookupTest extends TestCase {
32 public class StrLookupTest {
3033
3134 //-----------------------------------------------------------------------
35 @Test
3236 public void testNoneLookup() {
3337 assertEquals(null, StrLookup.noneLookup().lookup(null));
3438 assertEquals(null, StrLookup.noneLookup().lookup(""));
3539 assertEquals(null, StrLookup.noneLookup().lookup("any"));
3640 }
3741
42 @Test
3843 public void testSystemProperiesLookup() {
3944 assertEquals(System.getProperty("os.name"), StrLookup.systemPropertiesLookup().lookup("os.name"));
4045 assertEquals(null, StrLookup.systemPropertiesLookup().lookup(""));
4247 try {
4348 StrLookup.systemPropertiesLookup().lookup(null);
4449 fail();
45 } catch (NullPointerException ex) {
50 } catch (final NullPointerException ex) {
4651 // expected
4752 }
4853 }
4954
55 @Test
5056 public void testMapLookup() {
51 Map<String, Object> map = new HashMap<String, Object>();
57 final Map<String, Object> map = new HashMap<String, Object>();
5258 map.put("key", "value");
5359 map.put("number", Integer.valueOf(2));
5460 assertEquals("value", StrLookup.mapLookup(map).lookup("key"));
5864 assertEquals(null, StrLookup.mapLookup(map).lookup("other"));
5965 }
6066
67 @Test
6168 public void testMapLookup_nullMap() {
62 Map<String, ?> map = null;
69 final Map<String, ?> map = null;
6370 assertEquals(null, StrLookup.mapLookup(map).lookup(null));
6471 assertEquals(null, StrLookup.mapLookup(map).lookup(""));
6572 assertEquals(null, StrLookup.mapLookup(map).lookup("any"));
1616
1717 package org.apache.commons.lang3.text;
1818
19 import junit.framework.TestCase;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertSame;
21 import static org.junit.Assert.assertTrue;
22
23 import org.junit.Test;
2024
2125 /**
2226 * Unit tests for {@link org.apache.commons.lang3.text.StrMatcher}.
2327 *
24 * @version $Id: StrMatcherTest.java 892118 2009-12-18 03:39:13Z sebb $
28 * @version $Id: StrMatcherTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2529 */
26 public class StrMatcherTest extends TestCase {
30 public class StrMatcherTest {
2731
2832 private static final char[] BUFFER1 = "0,1\t2 3\n\r\f\u0000'\"".toCharArray();
2933
3034 private static final char[] BUFFER2 = "abcdef".toCharArray();
3135
32 /**
33 * Create a new test case with the specified name.
34 *
35 * @param name the name
36 */
37 public StrMatcherTest(String name) {
38 super(name);
39 }
40
41 //-----------------------------------------------------------------------
36
37 //-----------------------------------------------------------------------
38 @Test
4239 public void testCommaMatcher() {
43 StrMatcher matcher = StrMatcher.commaMatcher();
40 final StrMatcher matcher = StrMatcher.commaMatcher();
4441 assertSame(matcher, StrMatcher.commaMatcher());
4542 assertEquals(0, matcher.isMatch(BUFFER1, 0));
4643 assertEquals(1, matcher.isMatch(BUFFER1, 1));
4845 }
4946
5047 //-----------------------------------------------------------------------
48 @Test
5149 public void testTabMatcher() {
52 StrMatcher matcher = StrMatcher.tabMatcher();
50 final StrMatcher matcher = StrMatcher.tabMatcher();
5351 assertSame(matcher, StrMatcher.tabMatcher());
5452 assertEquals(0, matcher.isMatch(BUFFER1, 2));
5553 assertEquals(1, matcher.isMatch(BUFFER1, 3));
5755 }
5856
5957 //-----------------------------------------------------------------------
58 @Test
6059 public void testSpaceMatcher() {
61 StrMatcher matcher = StrMatcher.spaceMatcher();
60 final StrMatcher matcher = StrMatcher.spaceMatcher();
6261 assertSame(matcher, StrMatcher.spaceMatcher());
6362 assertEquals(0, matcher.isMatch(BUFFER1, 4));
6463 assertEquals(1, matcher.isMatch(BUFFER1, 5));
6665 }
6766
6867 //-----------------------------------------------------------------------
68 @Test
6969 public void testSplitMatcher() {
70 StrMatcher matcher = StrMatcher.splitMatcher();
70 final StrMatcher matcher = StrMatcher.splitMatcher();
7171 assertSame(matcher, StrMatcher.splitMatcher());
7272 assertEquals(0, matcher.isMatch(BUFFER1, 2));
7373 assertEquals(1, matcher.isMatch(BUFFER1, 3));
8181 }
8282
8383 //-----------------------------------------------------------------------
84 @Test
8485 public void testTrimMatcher() {
85 StrMatcher matcher = StrMatcher.trimMatcher();
86 final StrMatcher matcher = StrMatcher.trimMatcher();
8687 assertSame(matcher, StrMatcher.trimMatcher());
8788 assertEquals(0, matcher.isMatch(BUFFER1, 2));
8889 assertEquals(1, matcher.isMatch(BUFFER1, 3));
9697 }
9798
9899 //-----------------------------------------------------------------------
100 @Test
99101 public void testSingleQuoteMatcher() {
100 StrMatcher matcher = StrMatcher.singleQuoteMatcher();
102 final StrMatcher matcher = StrMatcher.singleQuoteMatcher();
101103 assertSame(matcher, StrMatcher.singleQuoteMatcher());
102104 assertEquals(0, matcher.isMatch(BUFFER1, 10));
103105 assertEquals(1, matcher.isMatch(BUFFER1, 11));
105107 }
106108
107109 //-----------------------------------------------------------------------
110 @Test
108111 public void testDoubleQuoteMatcher() {
109 StrMatcher matcher = StrMatcher.doubleQuoteMatcher();
112 final StrMatcher matcher = StrMatcher.doubleQuoteMatcher();
110113 assertSame(matcher, StrMatcher.doubleQuoteMatcher());
111114 assertEquals(0, matcher.isMatch(BUFFER1, 11));
112115 assertEquals(1, matcher.isMatch(BUFFER1, 12));
113116 }
114117
115118 //-----------------------------------------------------------------------
119 @Test
116120 public void testQuoteMatcher() {
117 StrMatcher matcher = StrMatcher.quoteMatcher();
121 final StrMatcher matcher = StrMatcher.quoteMatcher();
118122 assertSame(matcher, StrMatcher.quoteMatcher());
119123 assertEquals(0, matcher.isMatch(BUFFER1, 10));
120124 assertEquals(1, matcher.isMatch(BUFFER1, 11));
122126 }
123127
124128 //-----------------------------------------------------------------------
129 @Test
125130 public void testNoneMatcher() {
126 StrMatcher matcher = StrMatcher.noneMatcher();
131 final StrMatcher matcher = StrMatcher.noneMatcher();
127132 assertSame(matcher, StrMatcher.noneMatcher());
128133 assertEquals(0, matcher.isMatch(BUFFER1, 0));
129134 assertEquals(0, matcher.isMatch(BUFFER1, 1));
141146 }
142147
143148 //-----------------------------------------------------------------------
149 @Test
144150 public void testCharMatcher_char() {
145 StrMatcher matcher = StrMatcher.charMatcher('c');
151 final StrMatcher matcher = StrMatcher.charMatcher('c');
146152 assertEquals(0, matcher.isMatch(BUFFER2, 0));
147153 assertEquals(0, matcher.isMatch(BUFFER2, 1));
148154 assertEquals(1, matcher.isMatch(BUFFER2, 2));
152158 }
153159
154160 //-----------------------------------------------------------------------
161 @Test
155162 public void testCharSetMatcher_String() {
156 StrMatcher matcher = StrMatcher.charSetMatcher("ace");
163 final StrMatcher matcher = StrMatcher.charSetMatcher("ace");
157164 assertEquals(1, matcher.isMatch(BUFFER2, 0));
158165 assertEquals(0, matcher.isMatch(BUFFER2, 1));
159166 assertEquals(1, matcher.isMatch(BUFFER2, 2));
166173 }
167174
168175 //-----------------------------------------------------------------------
176 @Test
169177 public void testCharSetMatcher_charArray() {
170 StrMatcher matcher = StrMatcher.charSetMatcher("ace".toCharArray());
178 final StrMatcher matcher = StrMatcher.charSetMatcher("ace".toCharArray());
171179 assertEquals(1, matcher.isMatch(BUFFER2, 0));
172180 assertEquals(0, matcher.isMatch(BUFFER2, 1));
173181 assertEquals(1, matcher.isMatch(BUFFER2, 2));
180188 }
181189
182190 //-----------------------------------------------------------------------
191 @Test
183192 public void testStringMatcher_String() {
184 StrMatcher matcher = StrMatcher.stringMatcher("bc");
193 final StrMatcher matcher = StrMatcher.stringMatcher("bc");
185194 assertEquals(0, matcher.isMatch(BUFFER2, 0));
186195 assertEquals(2, matcher.isMatch(BUFFER2, 1));
187196 assertEquals(0, matcher.isMatch(BUFFER2, 2));
193202 }
194203
195204 //-----------------------------------------------------------------------
205 @Test
196206 public void testMatcherIndices() {
197207 // remember that the API contract is tight for the isMatch() method
198208 // all the onus is on the caller, so invalid inputs are not
199209 // the concern of StrMatcher, and are not bugs
200 StrMatcher matcher = StrMatcher.stringMatcher("bc");
210 final StrMatcher matcher = StrMatcher.stringMatcher("bc");
201211 assertEquals(2, matcher.isMatch(BUFFER2, 1, 1, BUFFER2.length));
202212 assertEquals(2, matcher.isMatch(BUFFER2, 1, 0, 3));
203213 assertEquals(0, matcher.isMatch(BUFFER2, 1, 0, 2));
1616
1717 package org.apache.commons.lang3.text;
1818
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertNull;
22 import static org.junit.Assert.assertSame;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
1926 import java.util.HashMap;
2027 import java.util.Map;
2128 import java.util.Properties;
2229
23 import junit.framework.TestCase;
24
2530 import org.apache.commons.lang3.mutable.MutableObject;
31 import org.junit.After;
32 import org.junit.Before;
33 import org.junit.Test;
2634
2735 /**
2836 * Test class for StrSubstitutor.
2937 *
30 * @version $Id: StrSubstitutorTest.java 1088899 2011-04-05 05:31:27Z bayard $
38 * @version $Id: StrSubstitutorTest.java 1524541 2013-09-18 19:35:16Z oheger $
3139 */
32 public class StrSubstitutorTest extends TestCase {
40 public class StrSubstitutorTest {
3341
3442 private Map<String, String> values;
3543
36 @Override
37 protected void setUp() throws Exception {
38 super.setUp();
44 @Before
45 public void setUp() throws Exception {
3946 values = new HashMap<String, String>();
4047 values.put("animal", "quick brown fox");
4148 values.put("target", "lazy dog");
4249 }
4350
44 @Override
45 protected void tearDown() throws Exception {
46 super.tearDown();
51 @After
52 public void tearDown() throws Exception {
4753 values = null;
4854 }
4955
5157 /**
5258 * Tests simple key replace.
5359 */
60 @Test
5461 public void testReplaceSimple() {
5562 doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
5663 }
5865 /**
5966 * Tests simple key replace.
6067 */
68 @Test
6169 public void testReplaceSolo() {
6270 doTestReplace("quick brown fox", "${animal}", false);
6371 }
6573 /**
6674 * Tests replace with no variables.
6775 */
76 @Test
6877 public void testReplaceNoVariables() {
6978 doTestNoReplace("The balloon arrived.");
7079 }
7281 /**
7382 * Tests replace with null.
7483 */
84 @Test
7585 public void testReplaceNull() {
7686 doTestNoReplace(null);
7787 }
7989 /**
8090 * Tests replace with null.
8191 */
92 @Test
8293 public void testReplaceEmpty() {
8394 doTestNoReplace("");
8495 }
8697 /**
8798 * Tests key replace changing map after initialization (not recommended).
8899 */
100 @Test
89101 public void testReplaceChangedMap() {
90 StrSubstitutor sub = new StrSubstitutor(values);
102 final StrSubstitutor sub = new StrSubstitutor(values);
91103 values.put("target", "moon");
92104 assertEquals("The quick brown fox jumps over the moon.", sub.replace("The ${animal} jumps over the ${target}."));
93105 }
95107 /**
96108 * Tests unknown key replace.
97109 */
110 @Test
98111 public void testReplaceUnknownKey() {
99112 doTestReplace("The ${person} jumps over the lazy dog.", "The ${person} jumps over the ${target}.", true);
113 doTestReplace("The ${person} jumps over the lazy dog. 1234567890.", "The ${person} jumps over the ${target}. ${undefined.number:-1234567890}.", true);
100114 }
101115
102116 /**
103117 * Tests adjacent keys.
104118 */
119 @Test
105120 public void testReplaceAdjacentAtStart() {
106121 values.put("code", "GBP");
107122 values.put("amount", "12.50");
108 StrSubstitutor sub = new StrSubstitutor(values);
123 final StrSubstitutor sub = new StrSubstitutor(values);
109124 assertEquals("GBP12.50 charged", sub.replace("${code}${amount} charged"));
110125 }
111126
112127 /**
113128 * Tests adjacent keys.
114129 */
130 @Test
115131 public void testReplaceAdjacentAtEnd() {
116132 values.put("code", "GBP");
117133 values.put("amount", "12.50");
118 StrSubstitutor sub = new StrSubstitutor(values);
134 final StrSubstitutor sub = new StrSubstitutor(values);
119135 assertEquals("Amount is GBP12.50", sub.replace("Amount is ${code}${amount}"));
120136 }
121137
122138 /**
123139 * Tests simple recursive replace.
124140 */
141 @Test
125142 public void testReplaceRecursive() {
126143 values.put("animal", "${critter}");
127144 values.put("target", "${pet}");
132149 values.put("critterColor", "brown");
133150 values.put("critterType", "fox");
134151 doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
152
153 values.put("pet", "${petCharacteristicUnknown:-lazy} dog");
154 doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
135155 }
136156
137157 /**
138158 * Tests escaping.
139159 */
160 @Test
140161 public void testReplaceEscaping() {
141162 doTestReplace("The ${animal} jumps over the lazy dog.", "The $${animal} jumps over the ${target}.", true);
142163 }
144165 /**
145166 * Tests escaping.
146167 */
168 @Test
147169 public void testReplaceSoloEscaping() {
148170 doTestReplace("${animal}", "$${animal}", false);
149171 }
151173 /**
152174 * Tests complex escaping.
153175 */
176 @Test
154177 public void testReplaceComplexEscaping() {
155178 doTestReplace("The ${quick brown fox} jumps over the lazy dog.", "The $${${animal}} jumps over the ${target}.", true);
179 doTestReplace("The ${quick brown fox} jumps over the lazy dog. ${1234567890}.", "The $${${animal}} jumps over the ${target}. $${${undefined.number:-1234567890}}.", true);
156180 }
157181
158182 /**
159183 * Tests when no prefix or suffix.
160184 */
161 public void testReplaceNoPefixNoSuffix() {
185 @Test
186 public void testReplaceNoPrefixNoSuffix() {
162187 doTestReplace("The animal jumps over the lazy dog.", "The animal jumps over the ${target}.", true);
163188 }
164189
165190 /**
166191 * Tests when no incomplete prefix.
167192 */
168 public void testReplaceIncompletePefix() {
193 @Test
194 public void testReplaceIncompletePrefix() {
169195 doTestReplace("The {animal} jumps over the lazy dog.", "The {animal} jumps over the ${target}.", true);
170196 }
171197
172198 /**
173199 * Tests when prefix but no suffix.
174200 */
201 @Test
175202 public void testReplacePrefixNoSuffix() {
176203 doTestReplace("The ${animal jumps over the ${target} lazy dog.", "The ${animal jumps over the ${target} ${target}.", true);
177204 }
179206 /**
180207 * Tests when suffix but no prefix.
181208 */
209 @Test
182210 public void testReplaceNoPrefixSuffix() {
183211 doTestReplace("The animal} jumps over the lazy dog.", "The animal} jumps over the ${target}.", true);
184212 }
186214 /**
187215 * Tests when no variable name.
188216 */
217 @Test
189218 public void testReplaceEmptyKeys() {
190219 doTestReplace("The ${} jumps over the lazy dog.", "The ${} jumps over the ${target}.", true);
220 doTestReplace("The animal jumps over the lazy dog.", "The ${:-animal} jumps over the ${target}.", true);
191221 }
192222
193223 /**
194224 * Tests replace creates output same as input.
195225 */
226 @Test
196227 public void testReplaceToIdentical() {
197228 values.put("animal", "$${${thing}}");
198229 values.put("thing", "animal");
203234 * Tests a cyclic replace operation.
204235 * The cycle should be detected and cause an exception to be thrown.
205236 */
237 @Test
206238 public void testCyclicReplacement() {
207 Map<String, String> map = new HashMap<String, String>();
239 final Map<String, String> map = new HashMap<String, String>();
208240 map.put("animal", "${critter}");
209241 map.put("target", "${pet}");
210242 map.put("pet", "${petCharacteristic} dog");
217249 try {
218250 sub.replace("The ${animal} jumps over the ${target}.");
219251 fail("Cyclic replacement was not detected!");
220 } catch (IllegalStateException ex) {
252 } catch (final IllegalStateException ex) {
221253 // expected
222254 }
255
256 // also check even when default value is set.
257 map.put("critterType", "${animal:-fox}");
258 sub = new StrSubstitutor(map);
259 try {
260 sub.replace("The ${animal} jumps over the ${target}.");
261 fail("Cyclic replacement was not detected!");
262 } catch (final IllegalStateException ex) {
263 // expected
264 }
223265 }
224266
225267 /**
226268 * Tests interpolation with weird boundary patterns.
227269 */
270 @Test
228271 public void testReplaceWeirdPattens() {
229272 doTestNoReplace("");
230273 doTestNoReplace("${}");
248291 /**
249292 * Tests simple key replace.
250293 */
294 @Test
251295 public void testReplacePartialString_noReplace() {
252 StrSubstitutor sub = new StrSubstitutor();
296 final StrSubstitutor sub = new StrSubstitutor();
253297 assertEquals("${animal} jumps", sub.replace("The ${animal} jumps over the ${target}.", 4, 15));
254298 }
255299
256300 /**
257301 * Tests whether a variable can be replaced in a variable name.
258302 */
303 @Test
259304 public void testReplaceInVariable() {
260305 values.put("animal.1", "fox");
261306 values.put("animal.2", "mouse");
262307 values.put("species", "2");
263 StrSubstitutor sub = new StrSubstitutor(values);
308 final StrSubstitutor sub = new StrSubstitutor(values);
264309 sub.setEnableSubstitutionInVariables(true);
265310 assertEquals(
266311 "Wrong result (1)",
271316 "Wrong result (2)",
272317 "The fox jumps over the lazy dog.",
273318 sub.replace("The ${animal.${species}} jumps over the ${target}."));
319 assertEquals(
320 "Wrong result (3)",
321 "The fox jumps over the lazy dog.",
322 sub.replace("The ${unknown.animal.${unknown.species:-1}:-fox} jumps over the ${unknow.target:-lazy dog}."));
274323 }
275324
276325 /**
277326 * Tests whether substitution in variable names is disabled per default.
278327 */
328 @Test
279329 public void testReplaceInVariableDisabled() {
280330 values.put("animal.1", "fox");
281331 values.put("animal.2", "mouse");
282332 values.put("species", "2");
283 StrSubstitutor sub = new StrSubstitutor(values);
333 final StrSubstitutor sub = new StrSubstitutor(values);
284334 assertEquals(
285 "Wrong result",
335 "Wrong result (1)",
286336 "The ${animal.${species}} jumps over the lazy dog.",
287337 sub.replace("The ${animal.${species}} jumps over the ${target}."));
338 assertEquals(
339 "Wrong result (2)",
340 "The ${animal.${species:-1}} jumps over the lazy dog.",
341 sub.replace("The ${animal.${species:-1}} jumps over the ${target}."));
288342 }
289343
290344 /**
291345 * Tests complex and recursive substitution in variable names.
292346 */
347 @Test
293348 public void testReplaceInVariableRecursive() {
294349 values.put("animal.2", "brown fox");
295350 values.put("animal.1", "white mouse");
296351 values.put("color", "white");
297352 values.put("species.white", "1");
298353 values.put("species.brown", "2");
299 StrSubstitutor sub = new StrSubstitutor(values);
354 final StrSubstitutor sub = new StrSubstitutor(values);
300355 sub.setEnableSubstitutionInVariables(true);
301356 assertEquals(
302 "Wrong result",
357 "Wrong result (1)",
303358 "The white mouse jumps over the lazy dog.",
304359 sub.replace("The ${animal.${species.${color}}} jumps over the ${target}."));
360 assertEquals(
361 "Wrong result (2)",
362 "The brown fox jumps over the lazy dog.",
363 sub.replace("The ${animal.${species.${unknownColor:-brown}}} jumps over the ${target}."));
364 }
365
366 @Test
367 public void testDefaultValueDelimiters() {
368 final Map<String, String> map = new HashMap<String, String>();
369 map.put("animal", "fox");
370 map.put("target", "dog");
371
372 StrSubstitutor sub = new StrSubstitutor(map, "${", "}", '$');
373 assertEquals("The fox jumps over the lazy dog. 1234567890.",
374 sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number:-1234567890}."));
375
376 sub = new StrSubstitutor(map, "${", "}", '$', "?:");
377 assertEquals("The fox jumps over the lazy dog. 1234567890.",
378 sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number?:1234567890}."));
379
380 sub = new StrSubstitutor(map, "${", "}", '$', "||");
381 assertEquals("The fox jumps over the lazy dog. 1234567890.",
382 sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number||1234567890}."));
383
384 sub = new StrSubstitutor(map, "${", "}", '$', "!");
385 assertEquals("The fox jumps over the lazy dog. 1234567890.",
386 sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
387
388 sub = new StrSubstitutor(map, "${", "}", '$', "");
389 sub.setValueDelimiterMatcher(null);
390 assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
391 sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
392
393 sub = new StrSubstitutor(map, "${", "}", '$');
394 sub.setValueDelimiterMatcher(null);
395 assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
396 sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
305397 }
306398
307399 //-----------------------------------------------------------------------
308400 /**
309401 * Tests protected.
310402 */
403 @Test
311404 public void testResolveVariable() {
312405 final StrBuilder builder = new StrBuilder("Hi ${name}!");
313 Map<String, String> map = new HashMap<String, String>();
406 final Map<String, String> map = new HashMap<String, String>();
314407 map.put("name", "commons");
315 StrSubstitutor sub = new StrSubstitutor(map) {
408 final StrSubstitutor sub = new StrSubstitutor(map) {
316409 @Override
317 protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) {
410 protected String resolveVariable(final String variableName, final StrBuilder buf, final int startPos, final int endPos) {
318411 assertEquals("name", variableName);
319412 assertSame(builder, buf);
320413 assertEquals(3, startPos);
330423 /**
331424 * Tests constructor.
332425 */
426 @Test
333427 public void testConstructorNoArgs() {
334 StrSubstitutor sub = new StrSubstitutor();
428 final StrSubstitutor sub = new StrSubstitutor();
335429 assertEquals("Hi ${name}", sub.replace("Hi ${name}"));
336430 }
337431
338432 /**
339433 * Tests constructor.
340434 */
435 @Test
341436 public void testConstructorMapPrefixSuffix() {
342 Map<String, String> map = new HashMap<String, String>();
437 final Map<String, String> map = new HashMap<String, String>();
343438 map.put("name", "commons");
344 StrSubstitutor sub = new StrSubstitutor(map, "<", ">");
439 final StrSubstitutor sub = new StrSubstitutor(map, "<", ">");
345440 assertEquals("Hi < commons", sub.replace("Hi $< <name>"));
346441 }
347442
348443 /**
349444 * Tests constructor.
350445 */
446 @Test
351447 public void testConstructorMapFull() {
352 Map<String, String> map = new HashMap<String, String>();
448 final Map<String, String> map = new HashMap<String, String>();
353449 map.put("name", "commons");
354450 StrSubstitutor sub = new StrSubstitutor(map, "<", ">", '!');
355451 assertEquals("Hi < commons", sub.replace("Hi !< <name>"));
452 sub = new StrSubstitutor(map, "<", ">", '!', "||");
453 assertEquals("Hi < commons", sub.replace("Hi !< <name2||commons>"));
356454 }
357455
358456 //-----------------------------------------------------------------------
359457 /**
360458 * Tests get set.
361459 */
460 @Test
362461 public void testGetSetEscape() {
363 StrSubstitutor sub = new StrSubstitutor();
462 final StrSubstitutor sub = new StrSubstitutor();
364463 assertEquals('$', sub.getEscapeChar());
365464 sub.setEscapeChar('<');
366465 assertEquals('<', sub.getEscapeChar());
369468 /**
370469 * Tests get set.
371470 */
471 @Test
372472 public void testGetSetPrefix() {
373 StrSubstitutor sub = new StrSubstitutor();
374 assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
473 final StrSubstitutor sub = new StrSubstitutor();
474 assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
375475 sub.setVariablePrefix('<');
376 assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.CharMatcher);
476 assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.CharMatcher);
377477
378478 sub.setVariablePrefix("<<");
379 assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
479 assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
380480 try {
381481 sub.setVariablePrefix((String) null);
382482 fail();
383 } catch (IllegalArgumentException ex) {
483 } catch (final IllegalArgumentException ex) {
384484 // expected
385485 }
386 assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
387
388 StrMatcher matcher = StrMatcher.commaMatcher();
486 assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
487
488 final StrMatcher matcher = StrMatcher.commaMatcher();
389489 sub.setVariablePrefixMatcher(matcher);
390490 assertSame(matcher, sub.getVariablePrefixMatcher());
391491 try {
392492 sub.setVariablePrefixMatcher((StrMatcher) null);
393493 fail();
394 } catch (IllegalArgumentException ex) {
494 } catch (final IllegalArgumentException ex) {
395495 // expected
396496 }
397497 assertSame(matcher, sub.getVariablePrefixMatcher());
400500 /**
401501 * Tests get set.
402502 */
503 @Test
403504 public void testGetSetSuffix() {
404 StrSubstitutor sub = new StrSubstitutor();
405 assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
505 final StrSubstitutor sub = new StrSubstitutor();
506 assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
406507 sub.setVariableSuffix('<');
407 assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.CharMatcher);
508 assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.CharMatcher);
408509
409510 sub.setVariableSuffix("<<");
410 assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
511 assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
411512 try {
412513 sub.setVariableSuffix((String) null);
413514 fail();
414 } catch (IllegalArgumentException ex) {
515 } catch (final IllegalArgumentException ex) {
415516 // expected
416517 }
417 assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
418
419 StrMatcher matcher = StrMatcher.commaMatcher();
518 assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
519
520 final StrMatcher matcher = StrMatcher.commaMatcher();
420521 sub.setVariableSuffixMatcher(matcher);
421522 assertSame(matcher, sub.getVariableSuffixMatcher());
422523 try {
423524 sub.setVariableSuffixMatcher((StrMatcher) null);
424525 fail();
425 } catch (IllegalArgumentException ex) {
526 } catch (final IllegalArgumentException ex) {
426527 // expected
427528 }
428529 assertSame(matcher, sub.getVariableSuffixMatcher());
429530 }
430531
532 /**
533 * Tests get set.
534 */
535 @Test
536 public void testGetSetValueDelimiter() {
537 final StrSubstitutor sub = new StrSubstitutor();
538 assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
539 sub.setValueDelimiter(':');
540 assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.CharMatcher);
541
542 sub.setValueDelimiter("||");
543 assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
544 sub.setValueDelimiter((String) null);
545 assertNull(sub.getValueDelimiterMatcher());
546
547 final StrMatcher matcher = StrMatcher.commaMatcher();
548 sub.setValueDelimiterMatcher(matcher);
549 assertSame(matcher, sub.getValueDelimiterMatcher());
550 sub.setValueDelimiterMatcher((StrMatcher) null);
551 assertNull(sub.getValueDelimiterMatcher());
552 }
553
431554 //-----------------------------------------------------------------------
432555 /**
433556 * Tests static.
434557 */
558 @Test
435559 public void testStaticReplace() {
436 Map<String, String> map = new HashMap<String, String>();
560 final Map<String, String> map = new HashMap<String, String>();
437561 map.put("name", "commons");
438562 assertEquals("Hi commons!", StrSubstitutor.replace("Hi ${name}!", map));
439563 }
441565 /**
442566 * Tests static.
443567 */
568 @Test
444569 public void testStaticReplacePrefixSuffix() {
445 Map<String, String> map = new HashMap<String, String>();
570 final Map<String, String> map = new HashMap<String, String>();
446571 map.put("name", "commons");
447572 assertEquals("Hi commons!", StrSubstitutor.replace("Hi <name>!", map, "<", ">"));
448573 }
450575 /**
451576 * Tests interpolation with system properties.
452577 */
578 @Test
453579 public void testStaticReplaceSystemProperties() {
454 StrBuilder buf = new StrBuilder();
580 final StrBuilder buf = new StrBuilder();
455581 buf.append("Hi ").append(System.getProperty("user.name"));
456582 buf.append(", you are working with ");
457583 buf.append(System.getProperty("os.name"));
465591 /**
466592 * Test the replace of a properties object
467593 */
468 public void testSubstitutetDefaultProperties(){
469 String org = "${doesnotwork}";
470 System.setProperty("doesnotwork", "It work's!");
594 @Test
595 public void testSubstituteDefaultProperties(){
596 final String org = "${doesnotwork}";
597 System.setProperty("doesnotwork", "It works!");
471598
472599 // create a new Properties object with the System.getProperties as default
473 Properties props = new Properties(System.getProperties());
474
475 assertEquals("It work's!",StrSubstitutor.replace(org, props));
600 final Properties props = new Properties(System.getProperties());
601
602 assertEquals("It works!", StrSubstitutor.replace(org, props));
603 }
604
605 @Test
606 public void testSamePrefixAndSuffix() {
607 final Map<String, String> map = new HashMap<String, String>();
608 map.put("greeting", "Hello");
609 map.put(" there ", "XXX");
610 map.put("name", "commons");
611 assertEquals("Hi commons!", StrSubstitutor.replace("Hi @name@!", map, "@", "@"));
612 assertEquals("Hello there commons!", StrSubstitutor.replace("@greeting@ there @name@!", map, "@", "@"));
476613 }
477614
478615 //-----------------------------------------------------------------------
479 private void doTestReplace(String expectedResult, String replaceTemplate, boolean substring) {
480 String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1);
481 StrSubstitutor sub = new StrSubstitutor(values);
616 private void doTestReplace(final String expectedResult, final String replaceTemplate, final boolean substring) {
617 final String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1);
618 final StrSubstitutor sub = new StrSubstitutor(values);
482619
483620 // replace using String
484621 assertEquals(expectedResult, sub.replace(replaceTemplate));
487624 }
488625
489626 // replace using char[]
490 char[] chars = replaceTemplate.toCharArray();
627 final char[] chars = replaceTemplate.toCharArray();
491628 assertEquals(expectedResult, sub.replace(chars));
492629 if (substring) {
493630 assertEquals(expectedShortResult, sub.replace(chars, 1, chars.length - 2));
500637 assertEquals(expectedShortResult, sub.replace(buf, 1, buf.length() - 2));
501638 }
502639
640 // replace using StringBuilder
641 StringBuilder builder = new StringBuilder(replaceTemplate);
642 assertEquals(expectedResult, sub.replace(builder));
643 if (substring) {
644 assertEquals(expectedShortResult, sub.replace(builder, 1, builder.length() - 2));
645 }
646
503647 // replace using StrBuilder
504648 StrBuilder bld = new StrBuilder(replaceTemplate);
505649 assertEquals(expectedResult, sub.replace(bld));
508652 }
509653
510654 // replace using object
511 MutableObject<String> obj = new MutableObject<String>(replaceTemplate); // toString returns template
655 final MutableObject<String> obj = new MutableObject<String>(replaceTemplate); // toString returns template
512656 assertEquals(expectedResult, sub.replace(obj));
513657
514658 // replace in StringBuffer
515659 buf = new StringBuffer(replaceTemplate);
516 assertEquals(true, sub.replaceIn(buf));
660 assertTrue(sub.replaceIn(buf));
517661 assertEquals(expectedResult, buf.toString());
518662 if (substring) {
519663 buf = new StringBuffer(replaceTemplate);
520 assertEquals(true, sub.replaceIn(buf, 1, buf.length() - 2));
664 assertTrue(sub.replaceIn(buf, 1, buf.length() - 2));
521665 assertEquals(expectedResult, buf.toString()); // expect full result as remainder is untouched
666 }
667
668 // replace in StringBuilder
669 builder = new StringBuilder(replaceTemplate);
670 assertTrue(sub.replaceIn(builder));
671 assertEquals(expectedResult, builder.toString());
672 if (substring) {
673 builder = new StringBuilder(replaceTemplate);
674 assertTrue(sub.replaceIn(builder, 1, builder.length() - 2));
675 assertEquals(expectedResult, builder.toString()); // expect full result as remainder is untouched
522676 }
523677
524678 // replace in StrBuilder
525679 bld = new StrBuilder(replaceTemplate);
526 assertEquals(true, sub.replaceIn(bld));
680 assertTrue(sub.replaceIn(bld));
527681 assertEquals(expectedResult, bld.toString());
528682 if (substring) {
529683 bld = new StrBuilder(replaceTemplate);
530 assertEquals(true, sub.replaceIn(bld, 1, bld.length() - 2));
684 assertTrue(sub.replaceIn(bld, 1, bld.length() - 2));
531685 assertEquals(expectedResult, bld.toString()); // expect full result as remainder is untouched
532686 }
533687 }
534688
535 private void doTestNoReplace(String replaceTemplate) {
536 StrSubstitutor sub = new StrSubstitutor(values);
689 private void doTestNoReplace(final String replaceTemplate) {
690 final StrSubstitutor sub = new StrSubstitutor(values);
537691
538692 if (replaceTemplate == null) {
539693 assertEquals(null, sub.replace((String) null));
545699 assertEquals(null, sub.replace((StrBuilder) null));
546700 assertEquals(null, sub.replace((StrBuilder) null, 0, 100));
547701 assertEquals(null, sub.replace((Object) null));
548 assertEquals(false, sub.replaceIn((StringBuffer) null));
549 assertEquals(false, sub.replaceIn((StringBuffer) null, 0, 100));
550 assertEquals(false, sub.replaceIn((StrBuilder) null));
551 assertEquals(false, sub.replaceIn((StrBuilder) null, 0, 100));
702 assertFalse(sub.replaceIn((StringBuffer) null));
703 assertFalse(sub.replaceIn((StringBuffer) null, 0, 100));
704 assertFalse(sub.replaceIn((StrBuilder) null));
705 assertFalse(sub.replaceIn((StrBuilder) null, 0, 100));
552706 } else {
553707 assertEquals(replaceTemplate, sub.replace(replaceTemplate));
554 StrBuilder bld = new StrBuilder(replaceTemplate);
555 assertEquals(false, sub.replaceIn(bld));
708 final StrBuilder bld = new StrBuilder(replaceTemplate);
709 assertFalse(sub.replaceIn(bld));
556710 assertEquals(replaceTemplate, bld.toString());
557711 }
558712 }
1616
1717 package org.apache.commons.lang3.text;
1818
19 import org.junit.Test;
20
21 import static org.junit.Assert.*;
22
1923 import java.util.Arrays;
2024 import java.util.Collections;
2125 import java.util.List;
2226 import java.util.NoSuchElementException;
2327
24 import junit.framework.TestCase;
25
2628 import org.apache.commons.lang3.ArrayUtils;
2729 import org.apache.commons.lang3.ObjectUtils;
2830
3032 * Unit test for Tokenizer.
3133 *
3234 */
33 public class StrTokenizerTest extends TestCase {
35 @SuppressWarnings("deprecation") // deliberate use of deprecated code
36 public class StrTokenizerTest {
3437
3538 private static final String CSV_SIMPLE_FIXTURE = "A,b,c";
3639
3740 private static final String TSV_SIMPLE_FIXTURE = "A\tb\tc";
3841
39 /**
40 * JUnit constructor.
41 *
42 * @param name
43 */
44 public StrTokenizerTest(String name) {
45 super(name);
46 }
47
48 private void checkClone(StrTokenizer tokenizer) {
42 private void checkClone(final StrTokenizer tokenizer) {
4943 assertFalse(StrTokenizer.getCSVInstance() == tokenizer);
5044 assertFalse(StrTokenizer.getTSVInstance() == tokenizer);
5145 }
5246
5347 // -----------------------------------------------------------------------
48 @Test
5449 public void test1() {
5550
56 String input = "a;b;c;\"d;\"\"e\";f; ; ; ";
57 StrTokenizer tok = new StrTokenizer(input);
51 final String input = "a;b;c;\"d;\"\"e\";f; ; ; ";
52 final StrTokenizer tok = new StrTokenizer(input);
5853 tok.setDelimiterChar(';');
5954 tok.setQuoteChar('"');
6055 tok.setIgnoredMatcher(StrMatcher.trimMatcher());
6156 tok.setIgnoreEmptyTokens(false);
62 String tokens[] = tok.getTokenArray();
63
64 String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", "", "", "",};
57 final String tokens[] = tok.getTokenArray();
58
59 final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", "", "", "",};
6560
6661 assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
6762 for (int i = 0; i < expected.length; i++) {
7166
7267 }
7368
69 @Test
7470 public void test2() {
7571
76 String input = "a;b;c ;\"d;\"\"e\";f; ; ;";
77 StrTokenizer tok = new StrTokenizer(input);
72 final String input = "a;b;c ;\"d;\"\"e\";f; ; ;";
73 final StrTokenizer tok = new StrTokenizer(input);
7874 tok.setDelimiterChar(';');
7975 tok.setQuoteChar('"');
8076 tok.setIgnoredMatcher(StrMatcher.noneMatcher());
8177 tok.setIgnoreEmptyTokens(false);
82 String tokens[] = tok.getTokenArray();
83
84 String expected[] = new String[]{"a", "b", "c ", "d;\"e", "f", " ", " ", "",};
78 final String tokens[] = tok.getTokenArray();
79
80 final String expected[] = new String[]{"a", "b", "c ", "d;\"e", "f", " ", " ", "",};
8581
8682 assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
8783 for (int i = 0; i < expected.length; i++) {
9187
9288 }
9389
90 @Test
9491 public void test3() {
9592
96 String input = "a;b; c;\"d;\"\"e\";f; ; ;";
97 StrTokenizer tok = new StrTokenizer(input);
93 final String input = "a;b; c;\"d;\"\"e\";f; ; ;";
94 final StrTokenizer tok = new StrTokenizer(input);
9895 tok.setDelimiterChar(';');
9996 tok.setQuoteChar('"');
10097 tok.setIgnoredMatcher(StrMatcher.noneMatcher());
10198 tok.setIgnoreEmptyTokens(false);
102 String tokens[] = tok.getTokenArray();
103
104 String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", " ", " ", "",};
99 final String tokens[] = tok.getTokenArray();
100
101 final String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", " ", " ", "",};
105102
106103 assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
107104 for (int i = 0; i < expected.length; i++) {
111108
112109 }
113110
111 @Test
114112 public void test4() {
115113
116 String input = "a;b; c;\"d;\"\"e\";f; ; ;";
117 StrTokenizer tok = new StrTokenizer(input);
114 final String input = "a;b; c;\"d;\"\"e\";f; ; ;";
115 final StrTokenizer tok = new StrTokenizer(input);
118116 tok.setDelimiterChar(';');
119117 tok.setQuoteChar('"');
120118 tok.setIgnoredMatcher(StrMatcher.trimMatcher());
121119 tok.setIgnoreEmptyTokens(true);
122 String tokens[] = tok.getTokenArray();
123
124 String expected[] = new String[]{"a", "b", "c", "d;\"e", "f",};
120 final String tokens[] = tok.getTokenArray();
121
122 final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f",};
125123
126124 assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
127125 for (int i = 0; i < expected.length; i++) {
131129
132130 }
133131
132 @Test
134133 public void test5() {
135134
136 String input = "a;b; c;\"d;\"\"e\";f; ; ;";
137 StrTokenizer tok = new StrTokenizer(input);
135 final String input = "a;b; c;\"d;\"\"e\";f; ; ;";
136 final StrTokenizer tok = new StrTokenizer(input);
138137 tok.setDelimiterChar(';');
139138 tok.setQuoteChar('"');
140139 tok.setIgnoredMatcher(StrMatcher.trimMatcher());
141140 tok.setIgnoreEmptyTokens(false);
142141 tok.setEmptyTokenAsNull(true);
143 String tokens[] = tok.getTokenArray();
144
145 String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null,};
142 final String tokens[] = tok.getTokenArray();
143
144 final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null,};
146145
147146 assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
148147 for (int i = 0; i < expected.length; i++) {
152151
153152 }
154153
154 @Test
155155 public void test6() {
156156
157 String input = "a;b; c;\"d;\"\"e\";f; ; ;";
158 StrTokenizer tok = new StrTokenizer(input);
157 final String input = "a;b; c;\"d;\"\"e\";f; ; ;";
158 final StrTokenizer tok = new StrTokenizer(input);
159159 tok.setDelimiterChar(';');
160160 tok.setQuoteChar('"');
161161 tok.setIgnoredMatcher(StrMatcher.trimMatcher());
162162 tok.setIgnoreEmptyTokens(false);
163163 // tok.setTreatingEmptyAsNull(true);
164 String tokens[] = tok.getTokenArray();
165
166 String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", null, null, null,};
164 final String tokens[] = tok.getTokenArray();
165
166 final String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", null, null, null,};
167167
168168 int nextCount = 0;
169169 while (tok.hasNext()) {
187187
188188 }
189189
190 @Test
190191 public void test7() {
191192
192 String input = "a b c \"d e\" f ";
193 StrTokenizer tok = new StrTokenizer(input);
193 final String input = "a b c \"d e\" f ";
194 final StrTokenizer tok = new StrTokenizer(input);
194195 tok.setDelimiterMatcher(StrMatcher.spaceMatcher());
195196 tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
196197 tok.setIgnoredMatcher(StrMatcher.noneMatcher());
197198 tok.setIgnoreEmptyTokens(false);
198 String tokens[] = tok.getTokenArray();
199
200 String expected[] = new String[]{"a", "", "", "b", "c", "d e", "f", "",};
199 final String tokens[] = tok.getTokenArray();
200
201 final String expected[] = new String[]{"a", "", "", "b", "c", "d e", "f", "",};
201202
202203 assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
203204 for (int i = 0; i < expected.length; i++) {
207208
208209 }
209210
211 @Test
210212 public void test8() {
211213
212 String input = "a b c \"d e\" f ";
213 StrTokenizer tok = new StrTokenizer(input);
214 final String input = "a b c \"d e\" f ";
215 final StrTokenizer tok = new StrTokenizer(input);
214216 tok.setDelimiterMatcher(StrMatcher.spaceMatcher());
215217 tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
216218 tok.setIgnoredMatcher(StrMatcher.noneMatcher());
217219 tok.setIgnoreEmptyTokens(true);
218 String tokens[] = tok.getTokenArray();
219
220 String expected[] = new String[]{"a", "b", "c", "d e", "f",};
220 final String tokens[] = tok.getTokenArray();
221
222 final String expected[] = new String[]{"a", "b", "c", "d e", "f",};
221223
222224 assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
223225 for (int i = 0; i < expected.length; i++) {
227229
228230 }
229231
232 @Test
230233 public void testBasic1() {
231 String input = "a b c";
232 StrTokenizer tok = new StrTokenizer(input);
233 assertEquals("a", tok.next());
234 assertEquals("b", tok.next());
235 assertEquals("c", tok.next());
236 assertEquals(false, tok.hasNext());
237 }
238
234 final String input = "a b c";
235 final StrTokenizer tok = new StrTokenizer(input);
236 assertEquals("a", tok.next());
237 assertEquals("b", tok.next());
238 assertEquals("c", tok.next());
239 assertFalse(tok.hasNext());
240 }
241
242 @Test
239243 public void testBasic2() {
240 String input = "a \nb\fc";
241 StrTokenizer tok = new StrTokenizer(input);
242 assertEquals("a", tok.next());
243 assertEquals("b", tok.next());
244 assertEquals("c", tok.next());
245 assertEquals(false, tok.hasNext());
246 }
247
244 final String input = "a \nb\fc";
245 final StrTokenizer tok = new StrTokenizer(input);
246 assertEquals("a", tok.next());
247 assertEquals("b", tok.next());
248 assertEquals("c", tok.next());
249 assertFalse(tok.hasNext());
250 }
251
252 @Test
248253 public void testBasic3() {
249 String input = "a \nb\u0001\fc";
250 StrTokenizer tok = new StrTokenizer(input);
254 final String input = "a \nb\u0001\fc";
255 final StrTokenizer tok = new StrTokenizer(input);
251256 assertEquals("a", tok.next());
252257 assertEquals("b\u0001", tok.next());
253258 assertEquals("c", tok.next());
254 assertEquals(false, tok.hasNext());
255 }
256
259 assertFalse(tok.hasNext());
260 }
261
262 @Test
257263 public void testBasic4() {
258 String input = "a \"b\" c";
259 StrTokenizer tok = new StrTokenizer(input);
264 final String input = "a \"b\" c";
265 final StrTokenizer tok = new StrTokenizer(input);
260266 assertEquals("a", tok.next());
261267 assertEquals("\"b\"", tok.next());
262268 assertEquals("c", tok.next());
263 assertEquals(false, tok.hasNext());
264 }
265
269 assertFalse(tok.hasNext());
270 }
271
272 @Test
266273 public void testBasic5() {
267 String input = "a:b':c";
268 StrTokenizer tok = new StrTokenizer(input, ':', '\'');
274 final String input = "a:b':c";
275 final StrTokenizer tok = new StrTokenizer(input, ':', '\'');
269276 assertEquals("a", tok.next());
270277 assertEquals("b'", tok.next());
271278 assertEquals("c", tok.next());
272 assertEquals(false, tok.hasNext());
273 }
274
279 assertFalse(tok.hasNext());
280 }
281
282 @Test
275283 public void testBasicDelim1() {
276 String input = "a:b:c";
277 StrTokenizer tok = new StrTokenizer(input, ':');
278 assertEquals("a", tok.next());
279 assertEquals("b", tok.next());
280 assertEquals("c", tok.next());
281 assertEquals(false, tok.hasNext());
282 }
283
284 final String input = "a:b:c";
285 final StrTokenizer tok = new StrTokenizer(input, ':');
286 assertEquals("a", tok.next());
287 assertEquals("b", tok.next());
288 assertEquals("c", tok.next());
289 assertFalse(tok.hasNext());
290 }
291
292 @Test
284293 public void testBasicDelim2() {
285 String input = "a:b:c";
286 StrTokenizer tok = new StrTokenizer(input, ',');
294 final String input = "a:b:c";
295 final StrTokenizer tok = new StrTokenizer(input, ',');
287296 assertEquals("a:b:c", tok.next());
288 assertEquals(false, tok.hasNext());
289 }
290
297 assertFalse(tok.hasNext());
298 }
299
300 @Test
291301 public void testBasicEmpty1() {
292 String input = "a b c";
293 StrTokenizer tok = new StrTokenizer(input);
302 final String input = "a b c";
303 final StrTokenizer tok = new StrTokenizer(input);
294304 tok.setIgnoreEmptyTokens(false);
295305 assertEquals("a", tok.next());
296306 assertEquals("", tok.next());
297307 assertEquals("b", tok.next());
298308 assertEquals("c", tok.next());
299 assertEquals(false, tok.hasNext());
300 }
301
309 assertFalse(tok.hasNext());
310 }
311
312 @Test
302313 public void testBasicEmpty2() {
303 String input = "a b c";
304 StrTokenizer tok = new StrTokenizer(input);
314 final String input = "a b c";
315 final StrTokenizer tok = new StrTokenizer(input);
305316 tok.setIgnoreEmptyTokens(false);
306317 tok.setEmptyTokenAsNull(true);
307318 assertEquals("a", tok.next());
308319 assertEquals(null, tok.next());
309320 assertEquals("b", tok.next());
310321 assertEquals("c", tok.next());
311 assertEquals(false, tok.hasNext());
312 }
313
322 assertFalse(tok.hasNext());
323 }
324
325 @Test
314326 public void testBasicQuoted1() {
315 String input = "a 'b' c";
316 StrTokenizer tok = new StrTokenizer(input, ' ', '\'');
317 assertEquals("a", tok.next());
318 assertEquals("b", tok.next());
319 assertEquals("c", tok.next());
320 assertEquals(false, tok.hasNext());
321 }
322
327 final String input = "a 'b' c";
328 final StrTokenizer tok = new StrTokenizer(input, ' ', '\'');
329 assertEquals("a", tok.next());
330 assertEquals("b", tok.next());
331 assertEquals("c", tok.next());
332 assertFalse(tok.hasNext());
333 }
334
335 @Test
323336 public void testBasicQuoted2() {
324 String input = "a:'b':";
325 StrTokenizer tok = new StrTokenizer(input, ':', '\'');
337 final String input = "a:'b':";
338 final StrTokenizer tok = new StrTokenizer(input, ':', '\'');
326339 tok.setIgnoreEmptyTokens(false);
327340 tok.setEmptyTokenAsNull(true);
328341 assertEquals("a", tok.next());
329342 assertEquals("b", tok.next());
330343 assertEquals(null, tok.next());
331 assertEquals(false, tok.hasNext());
332 }
333
344 assertFalse(tok.hasNext());
345 }
346
347 @Test
334348 public void testBasicQuoted3() {
335 String input = "a:'b''c'";
336 StrTokenizer tok = new StrTokenizer(input, ':', '\'');
349 final String input = "a:'b''c'";
350 final StrTokenizer tok = new StrTokenizer(input, ':', '\'');
337351 tok.setIgnoreEmptyTokens(false);
338352 tok.setEmptyTokenAsNull(true);
339353 assertEquals("a", tok.next());
340354 assertEquals("b'c", tok.next());
341 assertEquals(false, tok.hasNext());
342 }
343
355 assertFalse(tok.hasNext());
356 }
357
358 @Test
344359 public void testBasicQuoted4() {
345 String input = "a: 'b' 'c' :d";
346 StrTokenizer tok = new StrTokenizer(input, ':', '\'');
360 final String input = "a: 'b' 'c' :d";
361 final StrTokenizer tok = new StrTokenizer(input, ':', '\'');
347362 tok.setTrimmerMatcher(StrMatcher.trimMatcher());
348363 tok.setIgnoreEmptyTokens(false);
349364 tok.setEmptyTokenAsNull(true);
350365 assertEquals("a", tok.next());
351366 assertEquals("b c", tok.next());
352367 assertEquals("d", tok.next());
353 assertEquals(false, tok.hasNext());
354 }
355
368 assertFalse(tok.hasNext());
369 }
370
371 @Test
356372 public void testBasicQuoted5() {
357 String input = "a: 'b'x'c' :d";
358 StrTokenizer tok = new StrTokenizer(input, ':', '\'');
373 final String input = "a: 'b'x'c' :d";
374 final StrTokenizer tok = new StrTokenizer(input, ':', '\'');
359375 tok.setTrimmerMatcher(StrMatcher.trimMatcher());
360376 tok.setIgnoreEmptyTokens(false);
361377 tok.setEmptyTokenAsNull(true);
362378 assertEquals("a", tok.next());
363379 assertEquals("bxc", tok.next());
364380 assertEquals("d", tok.next());
365 assertEquals(false, tok.hasNext());
366 }
367
381 assertFalse(tok.hasNext());
382 }
383
384 @Test
368385 public void testBasicQuoted6() {
369 String input = "a:'b'\"c':d";
370 StrTokenizer tok = new StrTokenizer(input, ':');
386 final String input = "a:'b'\"c':d";
387 final StrTokenizer tok = new StrTokenizer(input, ':');
371388 tok.setQuoteMatcher(StrMatcher.quoteMatcher());
372389 assertEquals("a", tok.next());
373390 assertEquals("b\"c:d", tok.next());
374 assertEquals(false, tok.hasNext());
375 }
376
391 assertFalse(tok.hasNext());
392 }
393
394 @Test
377395 public void testBasicQuoted7() {
378 String input = "a:\"There's a reason here\":b";
379 StrTokenizer tok = new StrTokenizer(input, ':');
396 final String input = "a:\"There's a reason here\":b";
397 final StrTokenizer tok = new StrTokenizer(input, ':');
380398 tok.setQuoteMatcher(StrMatcher.quoteMatcher());
381399 assertEquals("a", tok.next());
382400 assertEquals("There's a reason here", tok.next());
383401 assertEquals("b", tok.next());
384 assertEquals(false, tok.hasNext());
385 }
386
402 assertFalse(tok.hasNext());
403 }
404
405 @Test
387406 public void testBasicQuotedTrimmed1() {
388 String input = "a: 'b' :";
389 StrTokenizer tok = new StrTokenizer(input, ':', '\'');
407 final String input = "a: 'b' :";
408 final StrTokenizer tok = new StrTokenizer(input, ':', '\'');
390409 tok.setTrimmerMatcher(StrMatcher.trimMatcher());
391410 tok.setIgnoreEmptyTokens(false);
392411 tok.setEmptyTokenAsNull(true);
393412 assertEquals("a", tok.next());
394413 assertEquals("b", tok.next());
395414 assertEquals(null, tok.next());
396 assertEquals(false, tok.hasNext());
397 }
398
415 assertFalse(tok.hasNext());
416 }
417
418 @Test
399419 public void testBasicTrimmed1() {
400 String input = "a: b : ";
401 StrTokenizer tok = new StrTokenizer(input, ':');
420 final String input = "a: b : ";
421 final StrTokenizer tok = new StrTokenizer(input, ':');
402422 tok.setTrimmerMatcher(StrMatcher.trimMatcher());
403423 tok.setIgnoreEmptyTokens(false);
404424 tok.setEmptyTokenAsNull(true);
405425 assertEquals("a", tok.next());
406426 assertEquals("b", tok.next());
407427 assertEquals(null, tok.next());
408 assertEquals(false, tok.hasNext());
409 }
410
428 assertFalse(tok.hasNext());
429 }
430
431 @Test
411432 public void testBasicTrimmed2() {
412 String input = "a: b :";
413 StrTokenizer tok = new StrTokenizer(input, ':');
433 final String input = "a: b :";
434 final StrTokenizer tok = new StrTokenizer(input, ':');
414435 tok.setTrimmerMatcher(StrMatcher.stringMatcher(" "));
415436 tok.setIgnoreEmptyTokens(false);
416437 tok.setEmptyTokenAsNull(true);
417438 assertEquals("a", tok.next());
418439 assertEquals("b", tok.next());
419440 assertEquals(null, tok.next());
420 assertEquals(false, tok.hasNext());
421 }
422
441 assertFalse(tok.hasNext());
442 }
443
444 @Test
423445 public void testBasicIgnoreTrimmed1() {
424 String input = "a: bIGNOREc : ";
425 StrTokenizer tok = new StrTokenizer(input, ':');
446 final String input = "a: bIGNOREc : ";
447 final StrTokenizer tok = new StrTokenizer(input, ':');
426448 tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE"));
427449 tok.setTrimmerMatcher(StrMatcher.trimMatcher());
428450 tok.setIgnoreEmptyTokens(false);
430452 assertEquals("a", tok.next());
431453 assertEquals("bc", tok.next());
432454 assertEquals(null, tok.next());
433 assertEquals(false, tok.hasNext());
434 }
435
455 assertFalse(tok.hasNext());
456 }
457
458 @Test
436459 public void testBasicIgnoreTrimmed2() {
437 String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE ";
438 StrTokenizer tok = new StrTokenizer(input, ':');
460 final String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE ";
461 final StrTokenizer tok = new StrTokenizer(input, ':');
439462 tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE"));
440463 tok.setTrimmerMatcher(StrMatcher.trimMatcher());
441464 tok.setIgnoreEmptyTokens(false);
443466 assertEquals("a", tok.next());
444467 assertEquals("bc", tok.next());
445468 assertEquals(null, tok.next());
446 assertEquals(false, tok.hasNext());
447 }
448
469 assertFalse(tok.hasNext());
470 }
471
472 @Test
449473 public void testBasicIgnoreTrimmed3() {
450 String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE ";
451 StrTokenizer tok = new StrTokenizer(input, ':');
474 final String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE ";
475 final StrTokenizer tok = new StrTokenizer(input, ':');
452476 tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE"));
453477 tok.setIgnoreEmptyTokens(false);
454478 tok.setEmptyTokenAsNull(true);
455479 assertEquals("a", tok.next());
456480 assertEquals(" bc ", tok.next());
457481 assertEquals(" ", tok.next());
458 assertEquals(false, tok.hasNext());
459 }
460
482 assertFalse(tok.hasNext());
483 }
484
485 @Test
461486 public void testBasicIgnoreTrimmed4() {
462 String input = "IGNOREaIGNORE: IGNORE 'bIGNOREc'IGNORE'd' IGNORE : IGNORE ";
463 StrTokenizer tok = new StrTokenizer(input, ':', '\'');
487 final String input = "IGNOREaIGNORE: IGNORE 'bIGNOREc'IGNORE'd' IGNORE : IGNORE ";
488 final StrTokenizer tok = new StrTokenizer(input, ':', '\'');
464489 tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE"));
465490 tok.setTrimmerMatcher(StrMatcher.trimMatcher());
466491 tok.setIgnoreEmptyTokens(false);
468493 assertEquals("a", tok.next());
469494 assertEquals("bIGNOREcd", tok.next());
470495 assertEquals(null, tok.next());
471 assertEquals(false, tok.hasNext());
472 }
473
474 //-----------------------------------------------------------------------
496 assertFalse(tok.hasNext());
497 }
498
499 //-----------------------------------------------------------------------
500 @Test
475501 public void testListArray() {
476 String input = "a b c";
477 StrTokenizer tok = new StrTokenizer(input);
478 String[] array = tok.getTokenArray();
479 List<?> list = tok.getTokenList();
502 final String input = "a b c";
503 final StrTokenizer tok = new StrTokenizer(input);
504 final String[] array = tok.getTokenArray();
505 final List<?> list = tok.getTokenList();
480506
481507 assertEquals(Arrays.asList(array), list);
482508 assertEquals(3, list.size());
483509 }
484510
485511 //-----------------------------------------------------------------------
486 public void testCSV(String data) {
512 private void testCSV(final String data) {
487513 this.testXSVAbc(StrTokenizer.getCSVInstance(data));
488514 this.testXSVAbc(StrTokenizer.getCSVInstance(data.toCharArray()));
489515 }
490516
517 @Test
491518 public void testCSVEmpty() {
492519 this.testEmpty(StrTokenizer.getCSVInstance());
493520 this.testEmpty(StrTokenizer.getCSVInstance(""));
494521 }
495522
523 @Test
496524 public void testCSVSimple() {
497525 this.testCSV(CSV_SIMPLE_FIXTURE);
498526 }
499527
528 @Test
500529 public void testCSVSimpleNeedsTrim() {
501530 this.testCSV(" " + CSV_SIMPLE_FIXTURE);
502531 this.testCSV(" \n\t " + CSV_SIMPLE_FIXTURE);
503532 this.testCSV(" \n " + CSV_SIMPLE_FIXTURE + "\n\n\r");
504533 }
505534
506 void testEmpty(StrTokenizer tokenizer) {
535 void testEmpty(final StrTokenizer tokenizer) {
507536 this.checkClone(tokenizer);
508 assertEquals(false, tokenizer.hasNext());
509 assertEquals(false, tokenizer.hasPrevious());
537 assertFalse(tokenizer.hasNext());
538 assertFalse(tokenizer.hasPrevious());
510539 assertEquals(null, tokenizer.nextToken());
511540 assertEquals(0, tokenizer.size());
512541 try {
513542 tokenizer.next();
514543 fail();
515 } catch (NoSuchElementException ex) {}
516 }
517
544 } catch (final NoSuchElementException ex) {}
545 }
546
547 @Test
518548 public void testGetContent() {
519 String input = "a b c \"d e\" f ";
549 final String input = "a b c \"d e\" f ";
520550 StrTokenizer tok = new StrTokenizer(input);
521551 assertEquals(input, tok.getContent());
522552
528558 }
529559
530560 //-----------------------------------------------------------------------
561 @Test
531562 public void testChaining() {
532 StrTokenizer tok = new StrTokenizer();
563 final StrTokenizer tok = new StrTokenizer();
533564 assertEquals(tok, tok.reset());
534565 assertEquals(tok, tok.reset(""));
535566 assertEquals(tok, tok.reset(new char[0]));
549580 * Tests that the {@link StrTokenizer#clone()} clone method catches {@link CloneNotSupportedException} and returns
550581 * <code>null</code>.
551582 */
583 @Test
552584 public void testCloneNotSupportedException() {
553 Object notCloned = new StrTokenizer() {
585 final Object notCloned = new StrTokenizer() {
554586 @Override
555587 Object cloneReset() throws CloneNotSupportedException {
556588 throw new CloneNotSupportedException("test");
559591 assertNull(notCloned);
560592 }
561593
594 @Test
562595 public void testCloneNull() {
563 StrTokenizer tokenizer = new StrTokenizer((char[]) null);
596 final StrTokenizer tokenizer = new StrTokenizer((char[]) null);
564597 // Start sanity check
565598 assertEquals(null, tokenizer.nextToken());
566599 tokenizer.reset();
567600 assertEquals(null, tokenizer.nextToken());
568601 // End sanity check
569 StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone();
602 final StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone();
570603 tokenizer.reset();
571604 assertEquals(null, tokenizer.nextToken());
572605 assertEquals(null, clonedTokenizer.nextToken());
573606 }
574607
608 @Test
575609 public void testCloneReset() {
576 char[] input = new char[]{'a'};
577 StrTokenizer tokenizer = new StrTokenizer(input);
610 final char[] input = new char[]{'a'};
611 final StrTokenizer tokenizer = new StrTokenizer(input);
578612 // Start sanity check
579613 assertEquals("a", tokenizer.nextToken());
580614 tokenizer.reset(input);
581615 assertEquals("a", tokenizer.nextToken());
582616 // End sanity check
583 StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone();
617 final StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone();
584618 input[0] = 'b';
585619 tokenizer.reset(input);
586620 assertEquals("b", tokenizer.nextToken());
588622 }
589623
590624 // -----------------------------------------------------------------------
625 @Test
591626 public void testConstructor_String() {
592627 StrTokenizer tok = new StrTokenizer("a b");
593628 assertEquals("a", tok.next());
594629 assertEquals("b", tok.next());
595 assertEquals(false, tok.hasNext());
630 assertFalse(tok.hasNext());
596631
597632 tok = new StrTokenizer("");
598 assertEquals(false, tok.hasNext());
633 assertFalse(tok.hasNext());
599634
600635 tok = new StrTokenizer((String) null);
601 assertEquals(false, tok.hasNext());
602 }
603
604 //-----------------------------------------------------------------------
636 assertFalse(tok.hasNext());
637 }
638
639 //-----------------------------------------------------------------------
640 @Test
605641 public void testConstructor_String_char() {
606642 StrTokenizer tok = new StrTokenizer("a b", ' ');
607643 assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1));
608644 assertEquals("a", tok.next());
609645 assertEquals("b", tok.next());
610 assertEquals(false, tok.hasNext());
646 assertFalse(tok.hasNext());
611647
612648 tok = new StrTokenizer("", ' ');
613 assertEquals(false, tok.hasNext());
649 assertFalse(tok.hasNext());
614650
615651 tok = new StrTokenizer((String) null, ' ');
616 assertEquals(false, tok.hasNext());
617 }
618
619 //-----------------------------------------------------------------------
652 assertFalse(tok.hasNext());
653 }
654
655 //-----------------------------------------------------------------------
656 @Test
620657 public void testConstructor_String_char_char() {
621658 StrTokenizer tok = new StrTokenizer("a b", ' ', '"');
622659 assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1));
623660 assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1));
624661 assertEquals("a", tok.next());
625662 assertEquals("b", tok.next());
626 assertEquals(false, tok.hasNext());
663 assertFalse(tok.hasNext());
627664
628665 tok = new StrTokenizer("", ' ', '"');
629 assertEquals(false, tok.hasNext());
666 assertFalse(tok.hasNext());
630667
631668 tok = new StrTokenizer((String) null, ' ', '"');
632 assertEquals(false, tok.hasNext());
633 }
634
635 //-----------------------------------------------------------------------
669 assertFalse(tok.hasNext());
670 }
671
672 //-----------------------------------------------------------------------
673 @Test
636674 public void testConstructor_charArray() {
637675 StrTokenizer tok = new StrTokenizer("a b".toCharArray());
638676 assertEquals("a", tok.next());
639677 assertEquals("b", tok.next());
640 assertEquals(false, tok.hasNext());
678 assertFalse(tok.hasNext());
641679
642680 tok = new StrTokenizer(new char[0]);
643 assertEquals(false, tok.hasNext());
681 assertFalse(tok.hasNext());
644682
645683 tok = new StrTokenizer((char[]) null);
646 assertEquals(false, tok.hasNext());
647 }
648
649 //-----------------------------------------------------------------------
684 assertFalse(tok.hasNext());
685 }
686
687 //-----------------------------------------------------------------------
688 @Test
650689 public void testConstructor_charArray_char() {
651690 StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' ');
652691 assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1));
653692 assertEquals("a", tok.next());
654693 assertEquals("b", tok.next());
655 assertEquals(false, tok.hasNext());
694 assertFalse(tok.hasNext());
656695
657696 tok = new StrTokenizer(new char[0], ' ');
658 assertEquals(false, tok.hasNext());
697 assertFalse(tok.hasNext());
659698
660699 tok = new StrTokenizer((char[]) null, ' ');
661 assertEquals(false, tok.hasNext());
662 }
663
664 //-----------------------------------------------------------------------
700 assertFalse(tok.hasNext());
701 }
702
703 //-----------------------------------------------------------------------
704 @Test
665705 public void testConstructor_charArray_char_char() {
666706 StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' ', '"');
667707 assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1));
668708 assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1));
669709 assertEquals("a", tok.next());
670710 assertEquals("b", tok.next());
671 assertEquals(false, tok.hasNext());
711 assertFalse(tok.hasNext());
672712
673713 tok = new StrTokenizer(new char[0], ' ', '"');
674 assertEquals(false, tok.hasNext());
714 assertFalse(tok.hasNext());
675715
676716 tok = new StrTokenizer((char[]) null, ' ', '"');
677 assertEquals(false, tok.hasNext());
678 }
679
680 //-----------------------------------------------------------------------
717 assertFalse(tok.hasNext());
718 }
719
720 //-----------------------------------------------------------------------
721 @Test
681722 public void testReset() {
682 StrTokenizer tok = new StrTokenizer("a b c");
683 assertEquals("a", tok.next());
684 assertEquals("b", tok.next());
685 assertEquals("c", tok.next());
686 assertEquals(false, tok.hasNext());
723 final StrTokenizer tok = new StrTokenizer("a b c");
724 assertEquals("a", tok.next());
725 assertEquals("b", tok.next());
726 assertEquals("c", tok.next());
727 assertFalse(tok.hasNext());
687728
688729 tok.reset();
689730 assertEquals("a", tok.next());
690731 assertEquals("b", tok.next());
691732 assertEquals("c", tok.next());
692 assertEquals(false, tok.hasNext());
693 }
694
695 //-----------------------------------------------------------------------
733 assertFalse(tok.hasNext());
734 }
735
736 //-----------------------------------------------------------------------
737 @Test
696738 public void testReset_String() {
697 StrTokenizer tok = new StrTokenizer("x x x");
739 final StrTokenizer tok = new StrTokenizer("x x x");
698740 tok.reset("d e");
699741 assertEquals("d", tok.next());
700742 assertEquals("e", tok.next());
701 assertEquals(false, tok.hasNext());
743 assertFalse(tok.hasNext());
702744
703745 tok.reset((String) null);
704 assertEquals(false, tok.hasNext());
705 }
706
707 //-----------------------------------------------------------------------
746 assertFalse(tok.hasNext());
747 }
748
749 //-----------------------------------------------------------------------
750 @Test
708751 public void testReset_charArray() {
709 StrTokenizer tok = new StrTokenizer("x x x");
710
711 char[] array = new char[] {'a', 'b', 'c'};
752 final StrTokenizer tok = new StrTokenizer("x x x");
753
754 final char[] array = new char[] {'a', 'b', 'c'};
712755 tok.reset(array);
713756 assertEquals("abc", tok.next());
714 assertEquals(false, tok.hasNext());
757 assertFalse(tok.hasNext());
715758
716759 tok.reset((char[]) null);
717 assertEquals(false, tok.hasNext());
718 }
719
720 //-----------------------------------------------------------------------
760 assertFalse(tok.hasNext());
761 }
762
763 //-----------------------------------------------------------------------
764 @Test
721765 public void testTSV() {
722766 this.testXSVAbc(StrTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE));
723767 this.testXSVAbc(StrTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE.toCharArray()));
724768 }
725769
770 @Test
726771 public void testTSVEmpty() {
727772 this.testEmpty(StrTokenizer.getCSVInstance());
728773 this.testEmpty(StrTokenizer.getCSVInstance(""));
729774 }
730775
731 void testXSVAbc(StrTokenizer tokenizer) {
776 void testXSVAbc(final StrTokenizer tokenizer) {
732777 this.checkClone(tokenizer);
733778 assertEquals(-1, tokenizer.previousIndex());
734779 assertEquals(0, tokenizer.nextIndex());
753798 assertEquals(3, tokenizer.size());
754799 }
755800
801 @Test
756802 public void testIteration() {
757 StrTokenizer tkn = new StrTokenizer("a b c");
758 assertEquals(false, tkn.hasPrevious());
803 final StrTokenizer tkn = new StrTokenizer("a b c");
804 assertFalse(tkn.hasPrevious());
759805 try {
760806 tkn.previous();
761807 fail();
762 } catch (NoSuchElementException ex) {}
763 assertEquals(true, tkn.hasNext());
808 } catch (final NoSuchElementException ex) {}
809 assertTrue(tkn.hasNext());
764810
765811 assertEquals("a", tkn.next());
766812 try {
767813 tkn.remove();
768814 fail();
769 } catch (UnsupportedOperationException ex) {}
815 } catch (final UnsupportedOperationException ex) {}
770816 try {
771817 tkn.set("x");
772818 fail();
773 } catch (UnsupportedOperationException ex) {}
819 } catch (final UnsupportedOperationException ex) {}
774820 try {
775821 tkn.add("y");
776822 fail();
777 } catch (UnsupportedOperationException ex) {}
778 assertEquals(true, tkn.hasPrevious());
779 assertEquals(true, tkn.hasNext());
823 } catch (final UnsupportedOperationException ex) {}
824 assertTrue(tkn.hasPrevious());
825 assertTrue(tkn.hasNext());
780826
781827 assertEquals("b", tkn.next());
782 assertEquals(true, tkn.hasPrevious());
783 assertEquals(true, tkn.hasNext());
828 assertTrue(tkn.hasPrevious());
829 assertTrue(tkn.hasNext());
784830
785831 assertEquals("c", tkn.next());
786 assertEquals(true, tkn.hasPrevious());
787 assertEquals(false, tkn.hasNext());
832 assertTrue(tkn.hasPrevious());
833 assertFalse(tkn.hasNext());
788834
789835 try {
790836 tkn.next();
791837 fail();
792 } catch (NoSuchElementException ex) {}
793 assertEquals(true, tkn.hasPrevious());
794 assertEquals(false, tkn.hasNext());
795 }
796
797 //-----------------------------------------------------------------------
838 } catch (final NoSuchElementException ex) {}
839 assertTrue(tkn.hasPrevious());
840 assertFalse(tkn.hasNext());
841 }
842
843 //-----------------------------------------------------------------------
844 @Test
798845 public void testTokenizeSubclassInputChange() {
799 StrTokenizer tkn = new StrTokenizer("a b c d e") {
846 final StrTokenizer tkn = new StrTokenizer("a b c d e") {
800847 @Override
801 protected List<String> tokenize(char[] chars, int offset, int count) {
848 protected List<String> tokenize(final char[] chars, final int offset, final int count) {
802849 return super.tokenize("w x y z".toCharArray(), 2, 5);
803850 }
804851 };
807854 }
808855
809856 //-----------------------------------------------------------------------
857 @Test
810858 public void testTokenizeSubclassOutputChange() {
811 StrTokenizer tkn = new StrTokenizer("a b c") {
859 final StrTokenizer tkn = new StrTokenizer("a b c") {
812860 @Override
813 protected List<String> tokenize(char[] chars, int offset, int count) {
814 List<String> list = super.tokenize(chars, offset, count);
861 protected List<String> tokenize(final char[] chars, final int offset, final int count) {
862 final List<String> list = super.tokenize(chars, offset, count);
815863 Collections.reverse(list);
816864 return list;
817865 }
822870 }
823871
824872 //-----------------------------------------------------------------------
873 @Test
825874 public void testToString() {
826 StrTokenizer tkn = new StrTokenizer("a b c d e");
875 final StrTokenizer tkn = new StrTokenizer("a b c d e");
827876 assertEquals("StrTokenizer[not tokenized yet]", tkn.toString());
828877 tkn.next();
829878 assertEquals("StrTokenizer[a, b, c, d, e]", tkn.toString());
1515 */
1616 package org.apache.commons.lang3.text;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertTrue;
22
1823 import java.lang.reflect.Constructor;
1924 import java.lang.reflect.Modifier;
2025
21 import junit.framework.TestCase;
26 import org.junit.Test;
2227
2328 /**
2429 * Unit tests for WordUtils class.
2530 *
26 * @version $Id: WordUtilsTest.java 1088899 2011-04-05 05:31:27Z bayard $
31 * @version $Id: WordUtilsTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2732 */
28 public class WordUtilsTest extends TestCase {
29
30 public WordUtilsTest(String name) {
31 super(name);
32 }
33 public class WordUtilsTest {
3334
3435 //-----------------------------------------------------------------------
36 @Test
3537 public void testConstructor() {
3638 assertNotNull(new WordUtils());
37 Constructor<?>[] cons = WordUtils.class.getDeclaredConstructors();
39 final Constructor<?>[] cons = WordUtils.class.getDeclaredConstructors();
3840 assertEquals(1, cons.length);
39 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
40 assertEquals(true, Modifier.isPublic(WordUtils.class.getModifiers()));
41 assertEquals(false, Modifier.isFinal(WordUtils.class.getModifiers()));
41 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
42 assertTrue(Modifier.isPublic(WordUtils.class.getModifiers()));
43 assertFalse(Modifier.isFinal(WordUtils.class.getModifiers()));
4244 }
4345
4446 //-----------------------------------------------------------------------
47 @Test
4548 public void testWrap_StringInt() {
4649 assertEquals(null, WordUtils.wrap(null, 20));
4750 assertEquals(null, WordUtils.wrap(null, -1));
5053 assertEquals("", WordUtils.wrap("", -1));
5154
5255 // normal
53 String systemNewLine = System.getProperty("line.separator");
56 final String systemNewLine = System.getProperty("line.separator");
5457 String input = "Here is one line of text that is going to be wrapped after 20 columns.";
5558 String expected = "Here is one line of" + systemNewLine + "text that is going"
5659 + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns.";
6972 assertEquals(expected, WordUtils.wrap(input, 20));
7073 }
7174
75 @Test
7276 public void testWrap_StringIntStringBoolean() {
7377 assertEquals(null, WordUtils.wrap(null, 20, "\n", false));
7478 assertEquals(null, WordUtils.wrap(null, 20, "\n", true));
105109 assertEquals(expected, WordUtils.wrap(input, -1, "\n", false));
106110
107111 // system newline char
108 String systemNewLine = System.getProperty("line.separator");
112 final String systemNewLine = System.getProperty("line.separator");
109113 input = "Here is one line of text that is going to be wrapped after 20 columns.";
110114 expected = "Here is one line of" + systemNewLine + "text that is going" + systemNewLine
111115 + "to be wrapped after" + systemNewLine + "20 columns.";
148152 }
149153
150154 //-----------------------------------------------------------------------
155 @Test
151156 public void testCapitalize_String() {
152157 assertEquals(null, WordUtils.capitalize(null));
153158 assertEquals("", WordUtils.capitalize(""));
161166 assertEquals("I AM HERE 123", WordUtils.capitalize("I AM HERE 123") );
162167 }
163168
169 @Test
164170 public void testCapitalizeWithDelimiters_String() {
165171 assertEquals(null, WordUtils.capitalize(null, null));
166172 assertEquals("", WordUtils.capitalize("", new char[0]));
178184 assertEquals("I Am.fine", WordUtils.capitalize("i am.fine", null) );
179185 }
180186
187 @Test
181188 public void testCapitalizeFully_String() {
182189 assertEquals(null, WordUtils.capitalizeFully(null));
183190 assertEquals("", WordUtils.capitalizeFully(""));
191198 assertEquals("I Am Here 123", WordUtils.capitalizeFully("I AM HERE 123") );
192199 }
193200
201 @Test
194202 public void testCapitalizeFullyWithDelimiters_String() {
195203 assertEquals(null, WordUtils.capitalizeFully(null, null));
196204 assertEquals("", WordUtils.capitalizeFully("", new char[0]));
208216 assertEquals("I Am.fine", WordUtils.capitalizeFully("i am.fine", null) );
209217 }
210218
219 @Test
211220 public void testUncapitalize_String() {
212221 assertEquals(null, WordUtils.uncapitalize(null));
213222 assertEquals("", WordUtils.uncapitalize(""));
221230 assertEquals("i aM hERE 123", WordUtils.uncapitalize("I AM HERE 123") );
222231 }
223232
233 @Test
224234 public void testUncapitalizeWithDelimiters_String() {
225235 assertEquals(null, WordUtils.uncapitalize(null, null));
226236 assertEquals("", WordUtils.uncapitalize("", new char[0]));
239249 }
240250
241251 //-----------------------------------------------------------------------
252 @Test
242253 public void testInitials_String() {
243254 assertEquals(null, WordUtils.initials(null));
244255 assertEquals("", WordUtils.initials(""));
253264 }
254265
255266 // -----------------------------------------------------------------------
267 @Test
256268 public void testInitials_String_charArray() {
257269 char[] array = null;
258270 assertEquals(null, WordUtils.initials(null, array));
334346 }
335347
336348 // -----------------------------------------------------------------------
349 @Test
337350 public void testSwapCase_String() {
338351 assertEquals(null, WordUtils.swapCase(null));
339352 assertEquals("", WordUtils.swapCase(""));
346359 assertEquals("I AM here 123", WordUtils.swapCase("i am HERE 123") );
347360 assertEquals("i am here 123", WordUtils.swapCase("I AM HERE 123") );
348361
349 String test = "This String contains a TitleCase character: \u01C8";
350 String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
362 final String test = "This String contains a TitleCase character: \u01C8";
363 final String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
351364 assertEquals(expect, WordUtils.swapCase(test));
352365 }
353366
1616
1717 package org.apache.commons.lang3.text.translate;
1818
19 import static org.junit.Assert.assertTrue;
20
1921 import java.util.HashSet;
2022 import java.util.Set;
2123
22 import junit.framework.TestCase;
24 import org.junit.Test;
2325
2426 /**
2527 * Unit tests for {@link org.apache.commons.lang3.text.translate.EntityArrays}.
26 * @version $Id: EntityArraysTest.java 1034797 2010-11-13 16:31:08Z sebb $
28 * @version $Id: EntityArraysTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2729 */
28 public class EntityArraysTest extends TestCase {
30 public class EntityArraysTest {
2931
32 @Test
3033 public void testConstructorExists() {
3134 new EntityArrays();
3235 }
3336
3437 // LANG-659 - check arrays for duplicate entries
38 @Test
3539 public void testHTML40_EXTENDED_ESCAPE(){
36 Set<String> col0 = new HashSet<String>();
37 Set<String> col1 = new HashSet<String>();
38 String [][] sa = EntityArrays.HTML40_EXTENDED_ESCAPE();
40 final Set<String> col0 = new HashSet<String>();
41 final Set<String> col1 = new HashSet<String>();
42 final String [][] sa = EntityArrays.HTML40_EXTENDED_ESCAPE();
3943 for(int i =0; i <sa.length; i++){
4044 assertTrue("Already added entry 0: "+i+" "+sa[i][0],col0.add(sa[i][0]));
4145 assertTrue("Already added entry 1: "+i+" "+sa[i][1],col1.add(sa[i][1]));
4347 }
4448
4549 // LANG-658 - check arrays for duplicate entries
50 @Test
4651 public void testISO8859_1_ESCAPE(){
47 Set<String> col0 = new HashSet<String>();
48 Set<String> col1 = new HashSet<String>();
49 String [][] sa = EntityArrays.ISO8859_1_ESCAPE();
52 final Set<String> col0 = new HashSet<String>();
53 final Set<String> col1 = new HashSet<String>();
54 final String [][] sa = EntityArrays.ISO8859_1_ESCAPE();
5055 boolean success = true;
5156 for(int i =0; i <sa.length; i++){
52 boolean add0 = col0.add(sa[i][0]);
53 boolean add1 = col1.add(sa[i][1]);
57 final boolean add0 = col0.add(sa[i][0]);
58 final boolean add1 = col1.add(sa[i][1]);
5459 if (!add0) {
5560 success = false;
5661 System.out.println("Already added entry 0: "+i+" "+sa[i][0]+" "+sa[i][1]);
1616
1717 package org.apache.commons.lang3.text.translate;
1818
19 import static org.junit.Assert.assertEquals;
20
1921 import java.io.IOException;
2022 import java.io.StringWriter;
2123
22 import junit.framework.TestCase;
24 import org.junit.Test;
2325
2426 /**
2527 * Unit tests for {@link org.apache.commons.lang3.text.translate.LookupTranslator}.
26 * @version $Id: LookupTranslatorTest.java 1022749 2010-10-14 22:49:55Z ggregory $
28 * @version $Id: LookupTranslatorTest.java 1470822 2013-04-23 06:00:41Z bayard $
2729 */
28 public class LookupTranslatorTest extends TestCase {
30 public class LookupTranslatorTest {
2931
32 @Test
3033 public void testBasicLookup() throws IOException {
31 LookupTranslator lt = new LookupTranslator(new CharSequence[][] { { "one", "two" } });
32 StringWriter out = new StringWriter();
33 int result = lt.translate("one", 0, out);
34 final LookupTranslator lt = new LookupTranslator(new CharSequence[][] { { "one", "two" } });
35 final StringWriter out = new StringWriter();
36 final int result = lt.translate("one", 0, out);
37 assertEquals("Incorrect codepoint consumption", 3, result);
38 assertEquals("Incorrect value", "two", out.toString());
39 }
40
41 // Tests: https://issues.apache.org/jira/browse/LANG-882
42 @Test
43 public void testLang882() throws IOException {
44 final LookupTranslator lt = new LookupTranslator(new CharSequence[][] { { new StringBuffer("one"), new StringBuffer("two") } });
45 final StringWriter out = new StringWriter();
46 final int result = lt.translate(new StringBuffer("one"), 0, out);
3447 assertEquals("Incorrect codepoint consumption", 3, result);
3548 assertEquals("Incorrect value", "two", out.toString());
3649 }
1616
1717 package org.apache.commons.lang3.text.translate;
1818
19 import junit.framework.TestCase;
19 import static org.junit.Assert.assertEquals;
20
21 import org.junit.Test;
2022
2123 /**
2224 * Unit tests for {@link org.apache.commons.lang3.text.translate.NumericEntityEscaper}.
23 * @version $Id: NumericEntityEscaperTest.java 1142151 2011-07-02 04:06:23Z bayard $
25 * @version $Id: NumericEntityEscaperTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2426 */
25 public class NumericEntityEscaperTest extends TestCase {
27 public class NumericEntityEscaperTest {
2628
29 @Test
2730 public void testBelow() {
28 NumericEntityEscaper nee = NumericEntityEscaper.below('F');
31 final NumericEntityEscaper nee = NumericEntityEscaper.below('F');
2932
30 String input = "ADFGZ";
31 String result = nee.translate(input);
33 final String input = "ADFGZ";
34 final String result = nee.translate(input);
3235 assertEquals("Failed to escape numeric entities via the below method", "&#65;&#68;FGZ", result);
3336 }
3437
38 @Test
3539 public void testBetween() {
36 NumericEntityEscaper nee = NumericEntityEscaper.between('F', 'L');
40 final NumericEntityEscaper nee = NumericEntityEscaper.between('F', 'L');
3741
38 String input = "ADFGZ";
39 String result = nee.translate(input);
42 final String input = "ADFGZ";
43 final String result = nee.translate(input);
4044 assertEquals("Failed to escape numeric entities via the between method", "AD&#70;&#71;Z", result);
4145 }
4246
47 @Test
4348 public void testAbove() {
44 NumericEntityEscaper nee = NumericEntityEscaper.above('F');
49 final NumericEntityEscaper nee = NumericEntityEscaper.above('F');
4550
46 String input = "ADFGZ";
47 String result = nee.translate(input);
51 final String input = "ADFGZ";
52 final String result = nee.translate(input);
4853 assertEquals("Failed to escape numeric entities via the above method", "ADF&#71;&#90;", result);
4954 }
5055
5156 // See LANG-617
57 @Test
5258 public void testSupplementary() {
53 NumericEntityEscaper nee = new NumericEntityEscaper();
54 String input = "\uD803\uDC22";
55 String expected = "&#68642;";
59 final NumericEntityEscaper nee = new NumericEntityEscaper();
60 final String input = "\uD803\uDC22";
61 final String expected = "&#68642;";
5662
57 String result = nee.translate(input);
63 final String result = nee.translate(input);
5864 assertEquals("Failed to escape numeric entities supplementary characters", expected, result);
5965
6066 }
1616
1717 package org.apache.commons.lang3.text.translate;
1818
19 import junit.framework.TestCase;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.fail;
21
22 import org.junit.Test;
2023
2124 /**
2225 * Unit tests for {@link org.apache.commons.lang3.text.translate.NumericEntityUnescaper}.
23 * @version $Id: NumericEntityUnescaperTest.java 1143643 2011-07-07 03:47:17Z bayard $
26 * @version $Id: NumericEntityUnescaperTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2427 */
25 public class NumericEntityUnescaperTest extends TestCase {
28 public class NumericEntityUnescaperTest {
2629
30 @Test
2731 public void testSupplementaryUnescaping() {
28 NumericEntityUnescaper neu = new NumericEntityUnescaper();
29 String input = "&#68642;";
30 String expected = "\uD803\uDC22";
32 final NumericEntityUnescaper neu = new NumericEntityUnescaper();
33 final String input = "&#68642;";
34 final String expected = "\uD803\uDC22";
3135
32 String result = neu.translate(input);
36 final String result = neu.translate(input);
3337 assertEquals("Failed to unescape numeric entities supplementary characters", expected, result);
3438 }
3539
40 @Test
3641 public void testOutOfBounds() {
37 NumericEntityUnescaper neu = new NumericEntityUnescaper();
42 final NumericEntityUnescaper neu = new NumericEntityUnescaper();
3843
3944 assertEquals("Failed to ignore when last character is &", "Test &", neu.translate("Test &"));
4045 assertEquals("Failed to ignore when last character is &", "Test &#", neu.translate("Test &#"));
4247 assertEquals("Failed to ignore when last character is &", "Test &#X", neu.translate("Test &#X"));
4348 }
4449
50 @Test
4551 public void testUnfinishedEntity() {
4652 // parse it
4753 NumericEntityUnescaper neu = new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional);
6672 try {
6773 result = neu.translate(input);
6874 fail("IllegalArgumentException expected");
69 } catch(IllegalArgumentException iae) {
75 } catch(final IllegalArgumentException iae) {
7076 // expected
7177 }
7278 }
1616
1717 package org.apache.commons.lang3.text.translate;
1818
19 import junit.framework.TestCase;
19 import org.junit.Test;
20 import static org.junit.Assert.*;
2021
2122 /**
2223 * Unit tests for {@link org.apache.commons.lang3.text.translate.OctalUnescaper}.
2324 * @version $Id: OctalUnescaperTest.java 979392 2010-07-26 18:09:52Z mbenson $
2425 */
25 public class OctalUnescaperTest extends TestCase {
26 public class OctalUnescaperTest {
2627
28 @Test
2729 public void testBetween() {
28 OctalUnescaper oue = new OctalUnescaper(); //.between("1", "377");
30 final OctalUnescaper oue = new OctalUnescaper(); //.between("1", "377");
2931
3032 String input = "\\45";
3133 String result = oue.translate(input);
4143
4244 input = "\\378 and";
4345 result = oue.translate(input);
44 assertEquals("Failed to unescape octal characters via the between method", "\378 and", result);
46 assertEquals("Failed to unescape octal characters via the between method", "\37" + "8 and", result);
4547
4648 input = "\\378";
4749 result = oue.translate(input);
48 assertEquals("Failed to unescape octal characters via the between method", "\378", result);
50 assertEquals("Failed to unescape octal characters via the between method", "\37" + "8", result);
4951
5052 input = "\\1";
5153 result = oue.translate(input);
5254 assertEquals("Failed to unescape octal characters via the between method", "\1", result);
55
56 input = "\\036";
57 result = oue.translate(input);
58 assertEquals("Failed to unescape octal characters via the between method", "\036", result);
59
60 input = "\\0365";
61 result = oue.translate(input);
62 assertEquals("Failed to unescape octal characters via the between method", "\036" + "5", result);
63
64 input = "\\003";
65 result = oue.translate(input);
66 assertEquals("Failed to unescape octal characters via the between method", "\003", result);
67
68 input = "\\0003";
69 result = oue.translate(input);
70 assertEquals("Failed to unescape octal characters via the between method", "\000" + "3", result);
71
72 input = "\\279";
73 result = oue.translate(input);
74 assertEquals("Failed to unescape octal characters via the between method", "\279", result);
75
76 input = "\\999";
77 result = oue.translate(input);
78 assertEquals("Failed to ignore an out of range octal character via the between method", "\\999", result);
5379 }
5480
5581 }
1616
1717 package org.apache.commons.lang3.text.translate;
1818
19 import junit.framework.TestCase;
19 import static org.junit.Assert.assertEquals;
20
21 import org.junit.Test;
2022
2123 /**
2224 * Unit tests for {@link org.apache.commons.lang3.text.translate.UnicodeEscaper}.
23 * @version $Id: UnicodeEscaperTest.java 1148520 2011-07-19 20:53:23Z ggregory $
25 * @version $Id: UnicodeEscaperTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2426 */
25 public class UnicodeEscaperTest extends TestCase {
27 public class UnicodeEscaperTest {
2628
29 @Test
2730 public void testBelow() {
28 UnicodeEscaper ue = UnicodeEscaper.below('F');
31 final UnicodeEscaper ue = UnicodeEscaper.below('F');
2932
30 String input = "ADFGZ";
31 String result = ue.translate(input);
33 final String input = "ADFGZ";
34 final String result = ue.translate(input);
3235 assertEquals("Failed to escape Unicode characters via the below method", "\\u0041\\u0044FGZ", result);
3336 }
3437
38 @Test
3539 public void testBetween() {
36 UnicodeEscaper ue = UnicodeEscaper.between('F', 'L');
40 final UnicodeEscaper ue = UnicodeEscaper.between('F', 'L');
3741
38 String input = "ADFGZ";
39 String result = ue.translate(input);
42 final String input = "ADFGZ";
43 final String result = ue.translate(input);
4044 assertEquals("Failed to escape Unicode characters via the between method", "AD\\u0046\\u0047Z", result);
4145 }
4246
47 @Test
4348 public void testAbove() {
44 UnicodeEscaper ue = UnicodeEscaper.above('F');
49 final UnicodeEscaper ue = UnicodeEscaper.above('F');
4550
46 String input = "ADFGZ";
47 String result = ue.translate(input);
51 final String input = "ADFGZ";
52 final String result = ue.translate(input);
4853 assertEquals("Failed to escape Unicode characters via the above method", "ADF\\u0047\\u005A", result);
4954 }
5055 }
1616
1717 package org.apache.commons.lang3.text.translate;
1818
19 import junit.framework.TestCase;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.fail;
21
22 import org.junit.Test;
2023
2124 /**
2225 * Unit tests for {@link org.apache.commons.lang3.text.translate.UnicodeEscaper}.
23 * @version $Id: UnicodeUnescaperTest.java 1148520 2011-07-19 20:53:23Z ggregory $
26 * @version $Id: UnicodeUnescaperTest.java 1436770 2013-01-22 07:09:45Z ggregory $
2427 */
25 public class UnicodeUnescaperTest extends TestCase {
28 public class UnicodeUnescaperTest {
2629
2730 // Requested in LANG-507
31 @Test
2832 public void testUPlus() {
29 UnicodeUnescaper uu = new UnicodeUnescaper();
33 final UnicodeUnescaper uu = new UnicodeUnescaper();
3034
31 String input = "\\u+0047";
35 final String input = "\\u+0047";
3236 assertEquals("Failed to unescape Unicode characters with 'u+' notation", "G", uu.translate(input));
3337 }
3438
39 @Test
3540 public void testUuuuu() {
36 UnicodeUnescaper uu = new UnicodeUnescaper();
41 final UnicodeUnescaper uu = new UnicodeUnescaper();
3742
38 String input = "\\uuuuuuuu0047";
39 String result = uu.translate(input);
43 final String input = "\\uuuuuuuu0047";
44 final String result = uu.translate(input);
4045 assertEquals("Failed to unescape Unicode characters with many 'u' characters", "G", result);
4146 }
4247
48 @Test
4349 public void testLessThanFour() {
44 UnicodeUnescaper uu = new UnicodeUnescaper();
50 final UnicodeUnescaper uu = new UnicodeUnescaper();
4551
46 String input = "\\0047\\u006";
52 final String input = "\\0047\\u006";
4753 try {
4854 uu.translate(input);
4955 fail("A lack of digits in a Unicode escape sequence failed to throw an exception");
50 } catch(IllegalArgumentException iae) {
56 } catch(final IllegalArgumentException iae) {
5157 // expected
5258 }
5359 }
1515 */
1616 package org.apache.commons.lang3.time;
1717
18 import org.junit.Test;
19 import static org.junit.Assert.*;
1820 import java.lang.reflect.Constructor;
1921 import java.lang.reflect.Modifier;
2022 import java.util.Calendar;
2123 import java.util.Locale;
2224 import java.util.TimeZone;
2325
24 import junit.framework.TestCase;
25
2626 /**
2727 * TestCase for DateFormatUtils.
2828 *
2929 */
30 public class DateFormatUtilsTest extends TestCase {
31
32 public DateFormatUtilsTest(String s) {
33 super(s);
34 }
30 public class DateFormatUtilsTest {
3531
3632 //-----------------------------------------------------------------------
33 @Test
3734 public void testConstructor() {
3835 assertNotNull(new DateFormatUtils());
39 Constructor<?>[] cons = DateFormatUtils.class.getDeclaredConstructors();
36 final Constructor<?>[] cons = DateFormatUtils.class.getDeclaredConstructors();
4037 assertEquals(1, cons.length);
41 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
42 assertEquals(true, Modifier.isPublic(DateFormatUtils.class.getModifiers()));
43 assertEquals(false, Modifier.isFinal(DateFormatUtils.class.getModifiers()));
38 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
39 assertTrue(Modifier.isPublic(DateFormatUtils.class.getModifiers()));
40 assertFalse(Modifier.isFinal(DateFormatUtils.class.getModifiers()));
4441 }
4542
4643 //-----------------------------------------------------------------------
44 @Test
4745 public void testFormat() {
48 Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
46 final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
4947 c.set(2005,0,1,12,0,0);
5048 c.setTimeZone(TimeZone.getDefault());
51 StringBuffer buffer = new StringBuffer ();
52 int year = c.get(Calendar.YEAR);
53 int month = c.get(Calendar.MONTH) + 1;
54 int day = c.get(Calendar.DAY_OF_MONTH);
55 int hour = c.get(Calendar.HOUR_OF_DAY);
49 final StringBuilder buffer = new StringBuilder ();
50 final int year = c.get(Calendar.YEAR);
51 final int month = c.get(Calendar.MONTH) + 1;
52 final int day = c.get(Calendar.DAY_OF_MONTH);
53 final int hour = c.get(Calendar.HOUR_OF_DAY);
5654 buffer.append (year);
5755 buffer.append(month);
5856 buffer.append(day);
6765 }
6866
6967 //-----------------------------------------------------------------------
68 @Test
7069 public void testFormatCalendar() {
71 Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
70 final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
7271 c.set(2005,0,1,12,0,0);
7372 c.setTimeZone(TimeZone.getDefault());
74 StringBuffer buffer = new StringBuffer ();
75 int year = c.get(Calendar.YEAR);
76 int month = c.get(Calendar.MONTH) + 1;
77 int day = c.get(Calendar.DAY_OF_MONTH);
78 int hour = c.get(Calendar.HOUR_OF_DAY);
73 final StringBuilder buffer = new StringBuilder ();
74 final int year = c.get(Calendar.YEAR);
75 final int month = c.get(Calendar.MONTH) + 1;
76 final int day = c.get(Calendar.DAY_OF_MONTH);
77 final int hour = c.get(Calendar.HOUR_OF_DAY);
7978 buffer.append (year);
8079 buffer.append(month);
8180 buffer.append(day);
8988 assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH", Locale.US));
9089 }
9190
91 @Test
9292 public void testFormatUTC() {
93 Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
93 final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
9494 c.set(2005,0,1,12,0,0);
9595 assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern()));
9696
101101 assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime().getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), Locale.US));
102102 }
103103
104 @Test
104105 public void testDateTimeISO(){
105 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
106 Calendar cal = Calendar.getInstance(timeZone);
106 final TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
107 final Calendar cal = Calendar.getInstance(timeZone);
107108 cal.set(2002,1,23,9,11,12);
108109 String text = DateFormatUtils.format(cal.getTime(),
109110 DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), timeZone);
124125 assertEquals("2002-02-23T09:11:12-03:00", text);
125126 }
126127
128 @Test
127129 public void testDateISO(){
128 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
129 Calendar cal = Calendar.getInstance(timeZone);
130 final TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
131 final Calendar cal = Calendar.getInstance(timeZone);
130132 cal.set(2002,1,23,10,11,12);
131133 String text = DateFormatUtils.format(cal.getTime(),
132134 DateFormatUtils.ISO_DATE_FORMAT.getPattern(), timeZone);
147149 assertEquals("2002-02-23-03:00", text);
148150 }
149151
152 @Test
150153 public void testTimeISO(){
151 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
152 Calendar cal = Calendar.getInstance(timeZone);
154 final TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
155 final Calendar cal = Calendar.getInstance(timeZone);
153156 cal.set(2002,1,23,10,11,12);
154157 String text = DateFormatUtils.format(cal.getTime(),
155158 DateFormatUtils.ISO_TIME_FORMAT.getPattern(), timeZone);
170173 assertEquals("T10:11:12-03:00", text);
171174 }
172175
176 @Test
173177 public void testTimeNoTISO(){
174 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
175 Calendar cal = Calendar.getInstance(timeZone);
178 final TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
179 final Calendar cal = Calendar.getInstance(timeZone);
176180 cal.set(2002,1,23,10,11,12);
177181 String text = DateFormatUtils.format(cal.getTime(),
178182 DateFormatUtils.ISO_TIME_NO_T_FORMAT.getPattern(), timeZone);
193197 assertEquals("10:11:12-03:00", text);
194198 }
195199
200 @Test
196201 public void testSMTP(){
197 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
198 Calendar cal = Calendar.getInstance(timeZone);
202 final TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
203 final Calendar cal = Calendar.getInstance(timeZone);
199204 cal.set(2003,5,8,10,11,12);
200205 String text = DateFormatUtils.format(cal.getTime(),
201206 DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), timeZone,
1515 */
1616 package org.apache.commons.lang3.time;
1717
18 import org.junit.Test;
19 import org.junit.Before;
20 import static org.junit.Assert.*;
1821 import java.util.Calendar;
1922 import java.util.Date;
2023
21 import junit.framework.TestCase;
22
23 public class DateUtilsFragmentTest extends TestCase {
24 public class DateUtilsFragmentTest {
2425
2526 private static final int months = 7; // second final prime before 12
2627 private static final int days = 23; // second final prime before 31 (and valid)
3233 private Date aDate;
3334 private Calendar aCalendar;
3435
35 @Override
36 protected void setUp() {
36
37 @Before
38 public void setUp() {
3739 aCalendar = Calendar.getInstance();
3840 aCalendar.set(2005, months, days, hours, minutes, seconds);
3941 aCalendar.set(Calendar.MILLISECOND, millis);
4042 aDate = aCalendar.getTime();
4143 }
4244
45 @Test
4346 public void testNullDate() {
4447 try {
4548 DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND);
4649 fail();
47 } catch(IllegalArgumentException iae) {}
50 } catch(final IllegalArgumentException iae) {}
4851
4952 try {
5053 DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND);
5154 fail();
52 } catch(IllegalArgumentException iae) {}
55 } catch(final IllegalArgumentException iae) {}
5356
5457 try {
5558 DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND);
5659 fail();
57 } catch(IllegalArgumentException iae) {}
60 } catch(final IllegalArgumentException iae) {}
5861
5962 try {
6063 DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND);
6164 fail();
62 } catch(IllegalArgumentException iae) {}
65 } catch(final IllegalArgumentException iae) {}
6366
6467 try {
6568 DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND);
6669 fail();
67 } catch(IllegalArgumentException iae) {}
68 }
69
70 } catch(final IllegalArgumentException iae) {}
71 }
72
73 @Test
7074 public void testNullCalendar() {
7175 try {
7276 DateUtils.getFragmentInMilliseconds((Calendar) null, Calendar.MILLISECOND);
7377 fail();
74 } catch(IllegalArgumentException iae) {}
78 } catch(final IllegalArgumentException iae) {}
7579
7680 try {
7781 DateUtils.getFragmentInSeconds((Calendar) null, Calendar.MILLISECOND);
7882 fail();
79 } catch(IllegalArgumentException iae) {}
83 } catch(final IllegalArgumentException iae) {}
8084
8185 try {
8286 DateUtils.getFragmentInMinutes((Calendar) null, Calendar.MILLISECOND);
8387 fail();
84 } catch(IllegalArgumentException iae) {}
88 } catch(final IllegalArgumentException iae) {}
8589
8690 try {
8791 DateUtils.getFragmentInHours((Calendar) null, Calendar.MILLISECOND);
8892 fail();
89 } catch(IllegalArgumentException iae) {}
93 } catch(final IllegalArgumentException iae) {}
9094
9195 try {
9296 DateUtils.getFragmentInDays((Calendar) null, Calendar.MILLISECOND);
9397 fail();
94 } catch(IllegalArgumentException iae) {}
95 }
96
98 } catch(final IllegalArgumentException iae) {}
99 }
100
101 @Test
97102 public void testInvalidFragmentWithDate() {
98103 try {
99104 DateUtils.getFragmentInMilliseconds(aDate, 0);
100105 fail();
101 } catch(IllegalArgumentException iae) {}
106 } catch(final IllegalArgumentException iae) {}
102107
103108 try {
104109 DateUtils.getFragmentInSeconds(aDate, 0);
105110 fail();
106 } catch(IllegalArgumentException iae) {}
111 } catch(final IllegalArgumentException iae) {}
107112
108113 try {
109114 DateUtils.getFragmentInMinutes(aDate, 0);
110115 fail();
111 } catch(IllegalArgumentException iae) {}
116 } catch(final IllegalArgumentException iae) {}
112117
113118 try {
114119 DateUtils.getFragmentInHours(aDate, 0);
115120 fail();
116 } catch(IllegalArgumentException iae) {}
121 } catch(final IllegalArgumentException iae) {}
117122
118123 try {
119124 DateUtils.getFragmentInDays(aDate, 0);
120125 fail();
121 } catch(IllegalArgumentException iae) {}
122 }
123
126 } catch(final IllegalArgumentException iae) {}
127 }
128
129 @Test
124130 public void testInvalidFragmentWithCalendar() {
125131 try {
126132 DateUtils.getFragmentInMilliseconds(aCalendar, 0);
127133 fail();
128 } catch(IllegalArgumentException iae) {}
134 } catch(final IllegalArgumentException iae) {}
129135
130136 try {
131137 DateUtils.getFragmentInSeconds(aCalendar, 0);
132138 fail();
133 } catch(IllegalArgumentException iae) {}
139 } catch(final IllegalArgumentException iae) {}
134140
135141 try {
136142 DateUtils.getFragmentInMinutes(aCalendar, 0);
137143 fail();
138 } catch(IllegalArgumentException iae) {}
144 } catch(final IllegalArgumentException iae) {}
139145
140146 try {
141147 DateUtils.getFragmentInHours(aCalendar, 0);
142148 fail();
143 } catch(IllegalArgumentException iae) {}
149 } catch(final IllegalArgumentException iae) {}
144150
145151 try {
146152 DateUtils.getFragmentInDays(aCalendar, 0);
147153 fail();
148 } catch(IllegalArgumentException iae) {}
149 }
150
154 } catch(final IllegalArgumentException iae) {}
155 }
156
157 @Test
151158 public void testMillisecondFragmentInLargerUnitWithDate() {
152159 assertEquals(0, DateUtils.getFragmentInMilliseconds(aDate, Calendar.MILLISECOND));
153160 assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.MILLISECOND));
156163 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MILLISECOND));
157164 }
158165
166 @Test
159167 public void testMillisecondFragmentInLargerUnitWithCalendar() {
160168 assertEquals(0, DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MILLISECOND));
161169 assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.MILLISECOND));
164172 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MILLISECOND));
165173 }
166174
175 @Test
167176 public void testSecondFragmentInLargerUnitWithDate() {
168177 assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.SECOND));
169178 assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.SECOND));
171180 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.SECOND));
172181 }
173182
183 @Test
174184 public void testSecondFragmentInLargerUnitWithCalendar() {
175185 assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.SECOND));
176186 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.SECOND));
178188 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.SECOND));
179189 }
180190
191 @Test
181192 public void testMinuteFragmentInLargerUnitWithDate() {
182193 assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.MINUTE));
183194 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.MINUTE));
184195 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MINUTE));
185196 }
186197
198 @Test
187199 public void testMinuteFragmentInLargerUnitWithCalendar() {
188200 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MINUTE));
189201 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MINUTE));
190202 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MINUTE));
191203 }
192204
205 @Test
193206 public void testHourOfDayFragmentInLargerUnitWithDate() {
194207 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.HOUR_OF_DAY));
195208 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.HOUR_OF_DAY));
196209 }
197210
211 @Test
198212 public void testHourOfDayFragmentInLargerUnitWithCalendar() {
199213 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.HOUR_OF_DAY));
200214 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.HOUR_OF_DAY));
201215 }
202216
217 @Test
203218 public void testDayOfYearFragmentInLargerUnitWithDate() {
204219 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DAY_OF_YEAR));
205220 }
206221
222 @Test
207223 public void testDayOfYearFragmentInLargerUnitWithCalendar() {
208224 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DAY_OF_YEAR));
209225 }
210226
227 @Test
211228 public void testDateFragmentInLargerUnitWithDate() {
212229 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DATE));
213230 }
214231
232 @Test
215233 public void testDateFragmentInLargerUnitWithCalendar() {
216234 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DATE));
217235 }
218236
219237 //Calendar.SECOND as useful fragment
220238
239 @Test
221240 public void testMillisecondsOfSecondWithDate() {
222 long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.SECOND);
241 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.SECOND);
223242 assertEquals(millis, testResult);
224243 }
225244
245 @Test
226246 public void testMillisecondsOfSecondWithCalendar() {
227 long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.SECOND);
247 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.SECOND);
228248 assertEquals(millis, testResult);
229249 assertEquals(aCalendar.get(Calendar.MILLISECOND), testResult);
230250 }
231251
232252 //Calendar.MINUTE as useful fragment
233253
254 @Test
234255 public void testMillisecondsOfMinuteWithDate() {
235 long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MINUTE);
256 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MINUTE);
236257 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND), testResult);
237258 }
238259
260 @Test
239261 public void testMillisecondsOfMinuteWithCalender() {
240 long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MINUTE);
262 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MINUTE);
241263 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND), testResult);
242264 }
243265
266 @Test
244267 public void testSecondsofMinuteWithDate() {
245 long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MINUTE);
268 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MINUTE);
246269 assertEquals(seconds, testResult);
247270 }
248271
272 @Test
249273 public void testSecondsofMinuteWithCalendar() {
250 long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MINUTE);
274 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MINUTE);
251275 assertEquals(seconds, testResult);
252276 assertEquals(aCalendar.get(Calendar.SECOND), testResult);
253277 }
254278
255279 //Calendar.HOUR_OF_DAY as useful fragment
256280
281 @Test
257282 public void testMillisecondsOfHourWithDate() {
258 long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.HOUR_OF_DAY);
283 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.HOUR_OF_DAY);
259284 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult);
260285 }
261286
287 @Test
262288 public void testMillisecondsOfHourWithCalendar() {
263 long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.HOUR_OF_DAY);
289 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.HOUR_OF_DAY);
264290 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult);
265291 }
266292
293 @Test
267294 public void testSecondsofHourWithDate() {
268 long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY);
295 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY);
269296 assertEquals(
270297 seconds
271298 + (minutes
273300 testResult);
274301 }
275302
303 @Test
276304 public void testSecondsofHourWithCalendar() {
277 long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY);
305 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY);
278306 assertEquals(
279307 seconds
280308 + (minutes
282310 testResult);
283311 }
284312
313 @Test
285314 public void testMinutesOfHourWithDate() {
286 long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.HOUR_OF_DAY);
315 final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.HOUR_OF_DAY);
287316 assertEquals(minutes, testResult);
288317 }
289318
319 @Test
290320 public void testMinutesOfHourWithCalendar() {
291 long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.HOUR_OF_DAY);
321 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.HOUR_OF_DAY);
292322 assertEquals(minutes, testResult);
293323 }
294324
295325 //Calendar.DATE and Calendar.DAY_OF_YEAR as useful fragment
326 @Test
296327 public void testMillisecondsOfDayWithDate() {
297328 long testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DATE);
298 long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
329 final long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
299330 assertEquals(expectedValue, testresult);
300331 testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DAY_OF_YEAR);
301332 assertEquals(expectedValue, testresult);
302333 }
303334
335 @Test
304336 public void testMillisecondsOfDayWithCalendar() {
305337 long testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DATE);
306 long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
338 final long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
307339 assertEquals(expectedValue, testresult);
308340 testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DAY_OF_YEAR);
309341 assertEquals(expectedValue, testresult);
310342 }
311343
344 @Test
312345 public void testSecondsOfDayWithDate() {
313346 long testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DATE);
314 long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
347 final long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
315348 assertEquals(expectedValue, testresult);
316349 testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DAY_OF_YEAR);
317350 assertEquals(expectedValue, testresult);
318351 }
319352
353 @Test
320354 public void testSecondsOfDayWithCalendar() {
321355 long testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DATE);
322 long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
356 final long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
323357 assertEquals(expectedValue, testresult);
324358 testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DAY_OF_YEAR);
325359 assertEquals(expectedValue, testresult);
326360 }
327361
362 @Test
328363 public void testMinutesOfDayWithDate() {
329364 long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DATE);
330 long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
365 final long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
331366 assertEquals(expectedValue,testResult);
332367 testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DAY_OF_YEAR);
333368 assertEquals(expectedValue,testResult);
334369 }
335370
371 @Test
336372 public void testMinutesOfDayWithCalendar() {
337373 long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DATE);
338 long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
374 final long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
339375 assertEquals(expectedValue, testResult);
340376 testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DAY_OF_YEAR);
341377 assertEquals(expectedValue, testResult);
342378 }
343379
380 @Test
344381 public void testHoursOfDayWithDate() {
345382 long testResult = DateUtils.getFragmentInHours(aDate, Calendar.DATE);
346 long expectedValue = hours;
383 final long expectedValue = hours;
347384 assertEquals(expectedValue,testResult);
348385 testResult = DateUtils.getFragmentInHours(aDate, Calendar.DAY_OF_YEAR);
349386 assertEquals(expectedValue,testResult);
350387 }
351388
389 @Test
352390 public void testHoursOfDayWithCalendar() {
353391 long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DATE);
354 long expectedValue = hours;
392 final long expectedValue = hours;
355393 assertEquals(expectedValue, testResult);
356394 testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DAY_OF_YEAR);
357395 assertEquals(expectedValue, testResult);
359397
360398
361399 //Calendar.MONTH as useful fragment
400 @Test
362401 public void testMillisecondsOfMonthWithDate() {
363 long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH);
402 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH);
364403 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
365404 + (hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY),
366405 testResult);
367406 }
368407
408 @Test
369409 public void testMillisecondsOfMonthWithCalendar() {
370 long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MONTH);
410 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MONTH);
371411 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
372412 + (hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY),
373413 testResult);
374414 }
375415
416 @Test
376417 public void testSecondsOfMonthWithDate() {
377 long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH);
418 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH);
378419 assertEquals(
379420 seconds
380421 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
383424 testResult);
384425 }
385426
427 @Test
386428 public void testSecondsOfMonthWithCalendar() {
387 long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH);
429 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH);
388430 assertEquals(
389431 seconds
390432 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
393435 testResult);
394436 }
395437
438 @Test
396439 public void testMinutesOfMonthWithDate() {
397 long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH);
440 final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH);
398441 assertEquals(minutes
399442 + ((hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY))
400443 / DateUtils.MILLIS_PER_MINUTE,
401444 testResult);
402445 }
403446
447 @Test
404448 public void testMinutesOfMonthWithCalendar() {
405 long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH);
449 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH);
406450 assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY))
407451 / DateUtils.MILLIS_PER_MINUTE,
408452 testResult);
409453 }
410454
455 @Test
411456 public void testHoursOfMonthWithDate() {
412 long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH);
457 final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH);
413458 assertEquals(hours + ((days * DateUtils.MILLIS_PER_DAY))
414459 / DateUtils.MILLIS_PER_HOUR,
415460 testResult);
416461 }
417462
463 @Test
418464 public void testHoursOfMonthWithCalendar() {
419 long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH);
465 final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH);
420466 assertEquals( hours +((days * DateUtils.MILLIS_PER_DAY))
421467 / DateUtils.MILLIS_PER_HOUR,
422468 testResult);
423469 }
424470
425471 //Calendar.YEAR as useful fragment
472 @Test
426473 public void testMillisecondsOfYearWithDate() {
427 long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.YEAR);
428 Calendar cal = Calendar.getInstance();
474 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.YEAR);
475 final Calendar cal = Calendar.getInstance();
429476 cal.setTime(aDate);
430477 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
431478 + (hours * DateUtils.MILLIS_PER_HOUR) + (cal.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY),
432479 testResult);
433480 }
434481
482 @Test
435483 public void testMillisecondsOfYearWithCalendar() {
436 long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR);
484 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR);
437485 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
438486 + (hours * DateUtils.MILLIS_PER_HOUR) + (aCalendar.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY),
439487 testResult);
440488 }
441489
490 @Test
442491 public void testSecondsOfYearWithDate() {
443 long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR);
444 Calendar cal = Calendar.getInstance();
492 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR);
493 final Calendar cal = Calendar.getInstance();
445494 cal.setTime(aDate);
446495 assertEquals(
447496 seconds
451500 testResult);
452501 }
453502
503 @Test
454504 public void testSecondsOfYearWithCalendar() {
455 long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR);
505 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR);
456506 assertEquals(
457507 seconds
458508 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
461511 testResult);
462512 }
463513
514 @Test
464515 public void testMinutesOfYearWithDate() {
465 long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.YEAR);
466 Calendar cal = Calendar.getInstance();
516 final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.YEAR);
517 final Calendar cal = Calendar.getInstance();
467518 cal.setTime(aDate);
468519 assertEquals(minutes
469520 + ((hours * DateUtils.MILLIS_PER_HOUR) + (cal.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY))
471522 testResult);
472523 }
473524
525 @Test
474526 public void testMinutesOfYearWithCalendar() {
475 long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR);
527 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR);
476528 assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + (aCalendar.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY))
477529 / DateUtils.MILLIS_PER_MINUTE,
478530 testResult);
479531 }
480532
533 @Test
481534 public void testHoursOfYearWithDate() {
482 long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR);
483 Calendar cal = Calendar.getInstance();
535 final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR);
536 final Calendar cal = Calendar.getInstance();
484537 cal.setTime(aDate);
485538 assertEquals(hours + ((cal.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY))
486539 / DateUtils.MILLIS_PER_HOUR,
487540 testResult);
488541 }
489542
543 @Test
490544 public void testHoursOfYearWithCalendar() {
491 long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR);
545 final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR);
492546 assertEquals( hours +((aCalendar.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY))
493547 / DateUtils.MILLIS_PER_HOUR,
494548 testResult);
1515 */
1616 package org.apache.commons.lang3.time;
1717
18 import org.junit.Test;
19 import org.junit.Before;
20 import static org.junit.Assert.*;
1821 import java.text.DateFormat;
1922 import java.text.SimpleDateFormat;
2023 import java.util.Calendar;
2124 import java.util.Date;
2225 import java.util.Locale;
23
24 import junit.framework.TestCase;
2526
2627 /**
2728 * These Unit-tests will check all possible extremes when using some rounding-methods of DateUtils.
3435 * A month with 31 days will be rounded up from the 17th
3536 *
3637 * @since 3.0
37 * @version $Id: DateUtilsRoundingTest.java 1088899 2011-04-05 05:31:27Z bayard $
38 * @version $Id: DateUtilsRoundingTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3839 */
39 public class DateUtilsRoundingTest extends TestCase {
40 public class DateUtilsRoundingTest {
4041
4142 DateFormat dateTimeParser;
4243
5253 Calendar januaryOneCalendar;
5354 FastDateFormat fdf = DateFormatUtils.ISO_DATETIME_FORMAT;
5455
55 @Override
56 protected void setUp() throws Exception {
57 super.setUp();
56
57 @Before
58 public void setUp() throws Exception {
59
5860 dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH);
5961
6062 targetYearDate = dateTimeParser.parse("January 1, 2007 0:00:00.000");
7880 * @throws Exception
7981 * @since 3.0
8082 */
83 @Test
8184 public void testRoundYear() throws Exception {
8285 final int calendarField = Calendar.YEAR;
83 Date roundedUpDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
84 Date roundedDownDate = targetYearDate;
85 Date lastRoundedDownDate = dateTimeParser.parse("June 30, 2007 23:59:59.999");
86 final Date roundedUpDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
87 final Date roundedDownDate = targetYearDate;
88 final Date lastRoundedDownDate = dateTimeParser.parse("June 30, 2007 23:59:59.999");
8689 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
8790 }
8891
9497 * @throws Exception
9598 * @since 3.0
9699 */
100 @Test
97101 public void testRoundMonth() throws Exception {
98102 final int calendarField = Calendar.MONTH;
99103 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
137141 * @throws Exception
138142 * @since 3.0
139143 */
144 @Test
140145 public void testRoundSemiMonth() throws Exception {
141146 final int calendarField = DateUtils.SEMI_MONTH;
142147 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
204209 * @throws Exception
205210 * @since 3.0
206211 */
212 @Test
207213 public void testRoundDate() throws Exception {
208214 final int calendarField = Calendar.DATE;
209215 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
228234 * @throws Exception
229235 * @since 3.0
230236 */
237 @Test
231238 public void testRoundDayOfMonth() throws Exception {
232239 final int calendarField = Calendar.DAY_OF_MONTH;
233240 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
252259 * @throws Exception
253260 * @since 3.0
254261 */
262 @Test
255263 public void testRoundAmPm() throws Exception {
256264 final int calendarField = Calendar.AM_PM;
257265 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
283291 * @throws Exception
284292 * @since 3.0
285293 */
294 @Test
286295 public void testRoundHourOfDay() throws Exception {
287296 final int calendarField = Calendar.HOUR_OF_DAY;
288297 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
307316 * @throws Exception
308317 * @since 3.0
309318 */
319 @Test
310320 public void testRoundHour() throws Exception {
311321 final int calendarField = Calendar.HOUR;
312322 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
331341 * @throws Exception
332342 * @since 3.0
333343 */
344 @Test
334345 public void testRoundMinute() throws Exception {
335346 final int calendarField = Calendar.MINUTE;
336347 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
355366 * @throws Exception
356367 * @since 3.0
357368 */
369 @Test
358370 public void testRoundSecond() throws Exception {
359371 final int calendarField = Calendar.SECOND;
360372 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
379391 * @throws Exception
380392 * @since 3.0
381393 */
394 @Test
382395 public void testRoundMilliSecond() throws Exception {
383396 final int calendarField = Calendar.MILLISECOND;
384397 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
399412 * @throws Exception
400413 * @since 3.0
401414 */
415 @Test
402416 public void testTruncateYear() throws Exception {
403417 final int calendarField = Calendar.YEAR;
404 Date lastTruncateDate = dateTimeParser.parse("December 31, 2007 23:59:59.999");
418 final Date lastTruncateDate = dateTimeParser.parse("December 31, 2007 23:59:59.999");
405419 baseTruncateTest(targetYearDate, lastTruncateDate, calendarField);
406420 }
407421
411425 * @throws Exception
412426 * @since 3.0
413427 */
428 @Test
414429 public void testTruncateMonth() throws Exception {
415430 final int calendarField = Calendar.MONTH;
416 Date truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
417 Date lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999");
431 final Date truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
432 final Date lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999");
418433 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
419434 }
420435
425440 * @throws Exception
426441 * @since 3.0
427442 */
443 @Test
428444 public void testTruncateSemiMonth() throws Exception {
429445 final int calendarField = DateUtils.SEMI_MONTH;
430446 Date truncatedDate, lastTruncateDate;
477493 * @throws Exception
478494 * @since 3.0
479495 */
496 @Test
480497 public void testTruncateDate() throws Exception {
481498 final int calendarField = Calendar.DATE;
482 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
499 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
483500 baseTruncateTest(targetDateDate, lastTruncateDate, calendarField);
484501 }
485502
489506 * @throws Exception
490507 * @since 3.0
491508 */
509 @Test
492510 public void testTruncateDayOfMonth() throws Exception {
493511 final int calendarField = Calendar.DAY_OF_MONTH;
494 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
512 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
495513 baseTruncateTest(targetDayOfMonthDate, lastTruncateDate, calendarField);
496514 }
497515
502520 * @throws Exception
503521 * @since 3.0
504522 */
523 @Test
505524 public void testTruncateAmPm() throws Exception {
506525 final int calendarField = Calendar.AM_PM;
507526
520539 * @throws Exception
521540 * @since 3.0
522541 */
542 @Test
523543 public void testTruncateHour() throws Exception {
524544 final int calendarField = Calendar.HOUR;
525 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
545 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
526546 baseTruncateTest(targetHourDate, lastTruncateDate, calendarField);
527547 }
528548
532552 * @throws Exception
533553 * @since 3.0
534554 */
555 @Test
535556 public void testTruncateHourOfDay() throws Exception {
536557 final int calendarField = Calendar.HOUR_OF_DAY;
537 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
558 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
538559 baseTruncateTest(targetHourOfDayDate, lastTruncateDate, calendarField);
539560 }
540561
544565 * @throws Exception
545566 * @since 3.0
546567 */
568 @Test
547569 public void testTruncateMinute() throws Exception {
548570 final int calendarField = Calendar.MINUTE;
549 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:59.999");
571 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:59.999");
550572 baseTruncateTest(targetMinuteDate, lastTruncateDate, calendarField);
551573 }
552574
556578 * @throws Exception
557579 * @since 3.0
558580 */
581 @Test
559582 public void testTruncateSecond() throws Exception {
560583 final int calendarField = Calendar.SECOND;
561 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:14.999");
584 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:14.999");
562585 baseTruncateTest(targetSecondDate, lastTruncateDate, calendarField);
563586 }
564587
568591 * @throws Exception
569592 * @since 3.0
570593 */
594 @Test
571595 public void testTruncateMilliSecond() throws Exception {
572596 final int calendarField = Calendar.MILLISECOND;
573597 baseTruncateTest(targetMilliSecondDate, targetMilliSecondDate, calendarField);
586610 * @since 3.0
587611 */
588612 protected void baseRoundTest(final Date roundedUpDate, final Date roundedDownDate, final Date lastRoundDownDate, final int calendarField) {
589 Date firstRoundUpDate = DateUtils.addMilliseconds(lastRoundDownDate, 1);
613 final Date firstRoundUpDate = DateUtils.addMilliseconds(lastRoundDownDate, 1);
590614
591615 //Date-comparison
592616 assertEquals(roundedDownDate, DateUtils.round(roundedDownDate, calendarField));
634658 * @since 3.0
635659 */
636660 protected void baseTruncateTest(final Date truncatedDate, final Date lastTruncateDate, final int calendarField) {
637 Date nextTruncateDate = DateUtils.addMilliseconds(lastTruncateDate, 1);
661 final Date nextTruncateDate = DateUtils.addMilliseconds(lastTruncateDate, 1);
638662
639663 //Date-comparison
640664 assertEquals("Truncating "+ fdf.format(truncatedDate) +" as Date with CalendarField-value "+ calendarField +" must return itself", truncatedDate, DateUtils.truncate(truncatedDate, calendarField));
674698 * @param calendarField
675699 * @since 3.0
676700 */
677 protected void roundToJanuaryFirst(Date minDate, Date maxDate, int calendarField) {
701 protected void roundToJanuaryFirst(final Date minDate, final Date maxDate, final int calendarField) {
678702 assertEquals("Rounding "+ fdf.format(januaryOneDate) +" as Date with CalendarField-value "+ calendarField +" must return itself", januaryOneDate, DateUtils.round(januaryOneDate, calendarField));
679703 assertEquals(januaryOneDate, DateUtils.round(minDate, calendarField));
680704 assertEquals(januaryOneDate, DateUtils.round(maxDate, calendarField));
681705
682 Calendar minCalendar = Calendar.getInstance();
706 final Calendar minCalendar = Calendar.getInstance();
683707 minCalendar.setTime(minDate);
684 Calendar maxCalendar = Calendar.getInstance();
708 final Calendar maxCalendar = Calendar.getInstance();
685709 maxCalendar.setTime(maxDate);
686710 assertEquals("Rounding "+ fdf.format(januaryOneCalendar) +" as Date with CalendarField-value "+ calendarField +" must return itself", januaryOneCalendar, DateUtils.round(januaryOneCalendar, calendarField));
687711 assertEquals(januaryOneCalendar, DateUtils.round(minCalendar, calendarField));
688712 assertEquals(januaryOneCalendar, DateUtils.round(maxCalendar, calendarField));
689713
690 Date toPrevRoundDate = DateUtils.addMilliseconds(minDate, -1);
691 Date toNextRoundDate = DateUtils.addMilliseconds(maxDate, 1);
714 final Date toPrevRoundDate = DateUtils.addMilliseconds(minDate, -1);
715 final Date toNextRoundDate = DateUtils.addMilliseconds(maxDate, 1);
692716 assertFalse(fdf.format(minDate) +" is not an lower-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toPrevRoundDate, calendarField)));
693717 assertFalse(fdf.format(maxDate) +" is not an upper-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toNextRoundDate, calendarField)));
694718
695 Calendar toPrevRoundCalendar = Calendar.getInstance();
719 final Calendar toPrevRoundCalendar = Calendar.getInstance();
696720 toPrevRoundCalendar.setTime(toPrevRoundDate);
697 Calendar toNextRoundCalendar = Calendar.getInstance();
721 final Calendar toNextRoundCalendar = Calendar.getInstance();
698722 toNextRoundCalendar.setTime(toNextRoundDate);
699723 assertFalse(fdf.format(minCalendar) +" is not an lower-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toPrevRoundDate, calendarField)));
700724 assertFalse(fdf.format(maxCalendar) +" is not an upper-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toNextRoundDate, calendarField)));
1717
1818 import static org.apache.commons.lang3.JavaVersion.JAVA_1_4;
1919
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertNotNull;
23 import static org.junit.Assert.assertNotSame;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
26
2027 import java.lang.reflect.Constructor;
2128 import java.lang.reflect.Modifier;
2229 import java.text.DateFormat;
3138 import java.util.TimeZone;
3239
3340 import junit.framework.AssertionFailedError;
34 import junit.framework.TestCase;
3541
3642 import org.apache.commons.lang3.SystemUtils;
43
44 import org.junit.Before;
45 import org.junit.Test;
3746
3847 /**
3948 * Unit tests {@link org.apache.commons.lang3.time.DateUtils}.
4049 *
4150 */
42 public class DateUtilsTest extends TestCase {
51 public class DateUtilsTest {
4352
4453 private static final long MILLIS_TEST;
4554 static {
46 GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2);
55 final GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2);
4756 cal.set(Calendar.MILLISECOND, 1);
4857 MILLIS_TEST = cal.getTime().getTime();
58 System.out.println("DateUtilsTest: Default Locale="+Locale.getDefault());
4959 }
5060
5161 DateFormat dateParser = null;
7989 TimeZone zone = null;
8090 TimeZone defaultZone = null;
8191
82 public DateUtilsTest(String name) {
83 super(name);
84 }
85
86 @Override
87 protected void setUp() throws Exception {
88 super.setUp();
92
93 @Before
94 public void setUp() throws Exception {
95
8996
9097 dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
9198 dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH);
138145 }
139146
140147 //-----------------------------------------------------------------------
148 @Test
141149 public void testConstructor() {
142150 assertNotNull(new DateUtils());
143 Constructor<?>[] cons = DateUtils.class.getDeclaredConstructors();
151 final Constructor<?>[] cons = DateUtils.class.getDeclaredConstructors();
144152 assertEquals(1, cons.length);
145 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
146 assertEquals(true, Modifier.isPublic(DateUtils.class.getModifiers()));
147 assertEquals(false, Modifier.isFinal(DateUtils.class.getModifiers()));
153 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
154 assertTrue(Modifier.isPublic(DateUtils.class.getModifiers()));
155 assertFalse(Modifier.isFinal(DateUtils.class.getModifiers()));
148156 }
149157
150158 //-----------------------------------------------------------------------
159 @Test
151160 public void testIsSameDay_Date() {
152 Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
153 Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
154 assertEquals(true, DateUtils.isSameDay(date1, date2));
155 date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
156 assertEquals(false, DateUtils.isSameDay(date1, date2));
157 date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
158 assertEquals(true, DateUtils.isSameDay(date1, date2));
159 date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime();
160 assertEquals(false, DateUtils.isSameDay(date1, date2));
161 Date datea = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
162 Date dateb = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
163 assertTrue(DateUtils.isSameDay(datea, dateb));
164 dateb = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
165 assertFalse(DateUtils.isSameDay(datea, dateb));
166 datea = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
167 assertTrue(DateUtils.isSameDay(datea, dateb));
168 dateb = new GregorianCalendar(2005, 6, 10, 13, 45).getTime();
169 assertFalse(DateUtils.isSameDay(datea, dateb));
161170 try {
162171 DateUtils.isSameDay((Date) null, (Date) null);
163172 fail();
164 } catch (IllegalArgumentException ex) {}
173 } catch (final IllegalArgumentException ex) {}
165174 }
166175
167176 //-----------------------------------------------------------------------
177 @Test
168178 public void testIsSameDay_Cal() {
169 GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45);
170 GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45);
171 assertEquals(true, DateUtils.isSameDay(cal1, cal2));
172 cal2.add(Calendar.DAY_OF_YEAR, 1);
173 assertEquals(false, DateUtils.isSameDay(cal1, cal2));
174 cal1.add(Calendar.DAY_OF_YEAR, 1);
175 assertEquals(true, DateUtils.isSameDay(cal1, cal2));
176 cal2.add(Calendar.YEAR, 1);
177 assertEquals(false, DateUtils.isSameDay(cal1, cal2));
179 final GregorianCalendar cala = new GregorianCalendar(2004, 6, 9, 13, 45);
180 final GregorianCalendar calb = new GregorianCalendar(2004, 6, 9, 13, 45);
181 assertTrue(DateUtils.isSameDay(cala, calb));
182 calb.add(Calendar.DAY_OF_YEAR, 1);
183 assertFalse(DateUtils.isSameDay(cala, calb));
184 cala.add(Calendar.DAY_OF_YEAR, 1);
185 assertTrue(DateUtils.isSameDay(cala, calb));
186 calb.add(Calendar.YEAR, 1);
187 assertFalse(DateUtils.isSameDay(cala, calb));
178188 try {
179189 DateUtils.isSameDay((Calendar) null, (Calendar) null);
180190 fail();
181 } catch (IllegalArgumentException ex) {}
191 } catch (final IllegalArgumentException ex) {}
182192 }
183193
184194 //-----------------------------------------------------------------------
195 @Test
185196 public void testIsSameInstant_Date() {
186 Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
187 Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
188 assertEquals(true, DateUtils.isSameInstant(date1, date2));
189 date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
190 assertEquals(false, DateUtils.isSameInstant(date1, date2));
191 date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
192 assertEquals(true, DateUtils.isSameInstant(date1, date2));
193 date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime();
194 assertEquals(false, DateUtils.isSameInstant(date1, date2));
197 Date datea = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
198 Date dateb = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
199 assertTrue(DateUtils.isSameInstant(datea, dateb));
200 dateb = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
201 assertFalse(DateUtils.isSameInstant(datea, dateb));
202 datea = new GregorianCalendar(2004, 6, 10, 13, 45).getTime();
203 assertTrue(DateUtils.isSameInstant(datea, dateb));
204 dateb = new GregorianCalendar(2005, 6, 10, 13, 45).getTime();
205 assertFalse(DateUtils.isSameInstant(datea, dateb));
195206 try {
196207 DateUtils.isSameInstant((Date) null, (Date) null);
197208 fail();
198 } catch (IllegalArgumentException ex) {}
209 } catch (final IllegalArgumentException ex) {}
199210 }
200211
201212 //-----------------------------------------------------------------------
213 @Test
202214 public void testIsSameInstant_Cal() {
203 GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
204 GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
205 cal1.set(2004, 6, 9, 13, 45, 0);
206 cal1.set(Calendar.MILLISECOND, 0);
207 cal2.set(2004, 6, 9, 13, 45, 0);
208 cal2.set(Calendar.MILLISECOND, 0);
209 assertEquals(false, DateUtils.isSameInstant(cal1, cal2));
210
211 cal2.set(2004, 6, 9, 11, 45, 0);
212 assertEquals(true, DateUtils.isSameInstant(cal1, cal2));
215 final GregorianCalendar cala = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
216 final GregorianCalendar calb = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
217 cala.set(2004, 6, 9, 13, 45, 0);
218 cala.set(Calendar.MILLISECOND, 0);
219 calb.set(2004, 6, 9, 13, 45, 0);
220 calb.set(Calendar.MILLISECOND, 0);
221 assertFalse(DateUtils.isSameInstant(cala, calb));
222
223 calb.set(2004, 6, 9, 11, 45, 0);
224 assertTrue(DateUtils.isSameInstant(cala, calb));
213225 try {
214226 DateUtils.isSameInstant((Calendar) null, (Calendar) null);
215227 fail();
216 } catch (IllegalArgumentException ex) {}
228 } catch (final IllegalArgumentException ex) {}
217229 }
218230
219231 //-----------------------------------------------------------------------
232 @Test
220233 public void testIsSameLocalTime_Cal() {
221 GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
222 GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
223 cal1.set(2004, 6, 9, 13, 45, 0);
224 cal1.set(Calendar.MILLISECOND, 0);
225 cal2.set(2004, 6, 9, 13, 45, 0);
226 cal2.set(Calendar.MILLISECOND, 0);
227 assertEquals(true, DateUtils.isSameLocalTime(cal1, cal2));
228
229 Calendar cal3 = Calendar.getInstance();
230 Calendar cal4 = Calendar.getInstance();
231 cal3.set(2004, 6, 9, 4, 0, 0);
232 cal4.set(2004, 6, 9, 16, 0, 0);
233 cal3.set(Calendar.MILLISECOND, 0);
234 cal4.set(Calendar.MILLISECOND, 0);
235 assertFalse("LANG-677", DateUtils.isSameLocalTime(cal3, cal4));
236
237 cal2.set(2004, 6, 9, 11, 45, 0);
238 assertEquals(false, DateUtils.isSameLocalTime(cal1, cal2));
234 final GregorianCalendar cala = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
235 final GregorianCalendar calb = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
236 cala.set(2004, 6, 9, 13, 45, 0);
237 cala.set(Calendar.MILLISECOND, 0);
238 calb.set(2004, 6, 9, 13, 45, 0);
239 calb.set(Calendar.MILLISECOND, 0);
240 assertTrue(DateUtils.isSameLocalTime(cala, calb));
241
242 final Calendar calc = Calendar.getInstance();
243 final Calendar cald = Calendar.getInstance();
244 calc.set(2004, 6, 9, 4, 0, 0);
245 cald.set(2004, 6, 9, 16, 0, 0);
246 calc.set(Calendar.MILLISECOND, 0);
247 cald.set(Calendar.MILLISECOND, 0);
248 assertFalse("LANG-677", DateUtils.isSameLocalTime(calc, cald));
249
250 calb.set(2004, 6, 9, 11, 45, 0);
251 assertFalse(DateUtils.isSameLocalTime(cala, calb));
239252 try {
240253 DateUtils.isSameLocalTime((Calendar) null, (Calendar) null);
241254 fail();
242 } catch (IllegalArgumentException ex) {}
255 } catch (final IllegalArgumentException ex) {}
243256 }
244257
245258 //-----------------------------------------------------------------------
259 @Test
246260 public void testParseDate() throws Exception {
247 GregorianCalendar cal = new GregorianCalendar(1972, 11, 3);
261 final GregorianCalendar cal = new GregorianCalendar(1972, 11, 3);
248262 String dateStr = "1972-12-03";
249 String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
263 final String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
250264 Date date = DateUtils.parseDate(dateStr, parsers);
251265 assertEquals(cal.getTime(), date);
252266
261275 try {
262276 DateUtils.parseDate("PURPLE", parsers);
263277 fail();
264 } catch (ParseException ex) {}
278 } catch (final ParseException ex) {}
265279 try {
266280 DateUtils.parseDate("197212AB", parsers);
267281 fail();
268 } catch (ParseException ex) {}
282 } catch (final ParseException ex) {}
269283 try {
270284 DateUtils.parseDate(null, parsers);
271285 fail();
272 } catch (IllegalArgumentException ex) {}
286 } catch (final IllegalArgumentException ex) {}
273287 try {
274288 DateUtils.parseDate(dateStr, (String[]) null);
275289 fail();
276 } catch (IllegalArgumentException ex) {}
290 } catch (final IllegalArgumentException ex) {}
277291 try {
278292 DateUtils.parseDate(dateStr, new String[0]);
279293 fail();
280 } catch (ParseException ex) {}
294 } catch (final ParseException ex) {}
281295 }
282296 // LANG-486
297 @Test
283298 public void testParseDateWithLeniency() throws Exception {
284 GregorianCalendar cal = new GregorianCalendar(1998, 6, 30);
285 String dateStr = "02 942, 1996";
286 String[] parsers = new String[] {"MM DDD, yyyy"};
299 final GregorianCalendar cal = new GregorianCalendar(1998, 6, 30);
300 final String dateStr = "02 942, 1996";
301 final String[] parsers = new String[] {"MM DDD, yyyy"};
287302
288303 Date date = DateUtils.parseDate(dateStr, parsers);
289304 assertEquals(cal.getTime(), date);
291306 try {
292307 date = DateUtils.parseDateStrictly(dateStr, parsers);
293308 fail();
294 } catch (ParseException ex) {}
295 }
296
297 //-----------------------------------------------------------------------
309 } catch (final ParseException ex) {}
310 }
311
312 //-----------------------------------------------------------------------
313 @Test
298314 public void testAddYears() throws Exception {
299 Date base = new Date(MILLIS_TEST);
315 final Date base = new Date(MILLIS_TEST);
300316 Date result = DateUtils.addYears(base, 0);
301317 assertNotSame(base, result);
302318 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
314330 }
315331
316332 //-----------------------------------------------------------------------
333 @Test
317334 public void testAddMonths() throws Exception {
318 Date base = new Date(MILLIS_TEST);
335 final Date base = new Date(MILLIS_TEST);
319336 Date result = DateUtils.addMonths(base, 0);
320337 assertNotSame(base, result);
321338 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
333350 }
334351
335352 //-----------------------------------------------------------------------
353 @Test
336354 public void testAddWeeks() throws Exception {
337 Date base = new Date(MILLIS_TEST);
355 final Date base = new Date(MILLIS_TEST);
338356 Date result = DateUtils.addWeeks(base, 0);
339357 assertNotSame(base, result);
340358 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
352370 }
353371
354372 //-----------------------------------------------------------------------
373 @Test
355374 public void testAddDays() throws Exception {
356 Date base = new Date(MILLIS_TEST);
375 final Date base = new Date(MILLIS_TEST);
357376 Date result = DateUtils.addDays(base, 0);
358377 assertNotSame(base, result);
359378 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
371390 }
372391
373392 //-----------------------------------------------------------------------
393 @Test
374394 public void testAddHours() throws Exception {
375 Date base = new Date(MILLIS_TEST);
395 final Date base = new Date(MILLIS_TEST);
376396 Date result = DateUtils.addHours(base, 0);
377397 assertNotSame(base, result);
378398 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
390410 }
391411
392412 //-----------------------------------------------------------------------
413 @Test
393414 public void testAddMinutes() throws Exception {
394 Date base = new Date(MILLIS_TEST);
415 final Date base = new Date(MILLIS_TEST);
395416 Date result = DateUtils.addMinutes(base, 0);
396417 assertNotSame(base, result);
397418 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
409430 }
410431
411432 //-----------------------------------------------------------------------
433 @Test
412434 public void testAddSeconds() throws Exception {
413 Date base = new Date(MILLIS_TEST);
435 final Date base = new Date(MILLIS_TEST);
414436 Date result = DateUtils.addSeconds(base, 0);
415437 assertNotSame(base, result);
416438 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
428450 }
429451
430452 //-----------------------------------------------------------------------
453 @Test
431454 public void testAddMilliseconds() throws Exception {
432 Date base = new Date(MILLIS_TEST);
455 final Date base = new Date(MILLIS_TEST);
433456 Date result = DateUtils.addMilliseconds(base, 0);
434457 assertNotSame(base, result);
435458 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
447470 }
448471
449472 // -----------------------------------------------------------------------
473 @Test
450474 public void testSetYears() throws Exception {
451 Date base = new Date(MILLIS_TEST);
475 final Date base = new Date(MILLIS_TEST);
452476 Date result = DateUtils.setYears(base, 2000);
453477 assertNotSame(base, result);
454478 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
466490 }
467491
468492 // -----------------------------------------------------------------------
493 @Test
469494 public void testSetMonths() throws Exception {
470 Date base = new Date(MILLIS_TEST);
495 final Date base = new Date(MILLIS_TEST);
471496 Date result = DateUtils.setMonths(base, 5);
472497 assertNotSame(base, result);
473498 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
480505
481506 try {
482507 result = DateUtils.setMonths(base, 12);
483 fail("DateUtils.setMonths did not throw an expected IllegalArguementException.");
484 } catch (IllegalArgumentException e) {
508 fail("DateUtils.setMonths did not throw an expected IllegalArgumentException.");
509 } catch (final IllegalArgumentException e) {
485510
486511 }
487512 }
488513
489514 // -----------------------------------------------------------------------
515 @Test
490516 public void testSetDays() throws Exception {
491 Date base = new Date(MILLIS_TEST);
517 final Date base = new Date(MILLIS_TEST);
492518 Date result = DateUtils.setDays(base, 1);
493519 assertNotSame(base, result);
494520 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
501527
502528 try {
503529 result = DateUtils.setDays(base, 32);
504 fail("DateUtils.setDays did not throw an expected IllegalArguementException.");
505 } catch (IllegalArgumentException e) {
530 fail("DateUtils.setDays did not throw an expected IllegalArgumentException.");
531 } catch (final IllegalArgumentException e) {
506532
507533 }
508534 }
509535
510536 // -----------------------------------------------------------------------
537 @Test
511538 public void testSetHours() throws Exception {
512 Date base = new Date(MILLIS_TEST);
539 final Date base = new Date(MILLIS_TEST);
513540 Date result = DateUtils.setHours(base, 0);
514541 assertNotSame(base, result);
515542 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
522549
523550 try {
524551 result = DateUtils.setHours(base, 24);
525 fail("DateUtils.setHours did not throw an expected IllegalArguementException.");
526 } catch (IllegalArgumentException e) {
552 fail("DateUtils.setHours did not throw an expected IllegalArgumentException.");
553 } catch (final IllegalArgumentException e) {
527554
528555 }
529556 }
530557
531558 // -----------------------------------------------------------------------
559 @Test
532560 public void testSetMinutes() throws Exception {
533 Date base = new Date(MILLIS_TEST);
561 final Date base = new Date(MILLIS_TEST);
534562 Date result = DateUtils.setMinutes(base, 0);
535563 assertNotSame(base, result);
536564 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
543571
544572 try {
545573 result = DateUtils.setMinutes(base, 60);
546 fail("DateUtils.setMinutes did not throw an expected IllegalArguementException.");
547 } catch (IllegalArgumentException e) {
574 fail("DateUtils.setMinutes did not throw an expected IllegalArgumentException.");
575 } catch (final IllegalArgumentException e) {
548576
549577 }
550578 }
551579
552580 // -----------------------------------------------------------------------
581 @Test
553582 public void testSetSeconds() throws Exception {
554 Date base = new Date(MILLIS_TEST);
583 final Date base = new Date(MILLIS_TEST);
555584 Date result = DateUtils.setSeconds(base, 0);
556585 assertNotSame(base, result);
557586 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
564593
565594 try {
566595 result = DateUtils.setSeconds(base, 60);
567 fail("DateUtils.setSeconds did not throw an expected IllegalArguementException.");
568 } catch (IllegalArgumentException e) {
596 fail("DateUtils.setSeconds did not throw an expected IllegalArgumentException.");
597 } catch (final IllegalArgumentException e) {
569598
570599 }
571600 }
572601
573602 // -----------------------------------------------------------------------
603 @Test
574604 public void testSetMilliseconds() throws Exception {
575 Date base = new Date(MILLIS_TEST);
605 final Date base = new Date(MILLIS_TEST);
576606 Date result = DateUtils.setMilliseconds(base, 0);
577607 assertNotSame(base, result);
578608 assertDate(base, 2000, 6, 5, 4, 3, 2, 1);
585615
586616 try {
587617 result = DateUtils.setMilliseconds(base, 1000);
588 fail("DateUtils.setMilliseconds did not throw an expected IllegalArguementException.");
589 } catch (IllegalArgumentException e) {
590
591 }
592 }
593
594 //-----------------------------------------------------------------------
595 private void assertDate(Date date, int year, int month, int day, int hour, int min, int sec, int mil) throws Exception {
596 GregorianCalendar cal = new GregorianCalendar();
618 fail("DateUtils.setMilliseconds did not throw an expected IllegalArgumentException.");
619 } catch (final IllegalArgumentException e) {
620
621 }
622 }
623
624 //-----------------------------------------------------------------------
625 private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception {
626 final GregorianCalendar cal = new GregorianCalendar();
597627 cal.setTime(date);
598628 assertEquals(year, cal.get(Calendar.YEAR));
599629 assertEquals(month, cal.get(Calendar.MONTH));
605635 }
606636
607637 //-----------------------------------------------------------------------
638 @Test
608639 public void testToCalendar() {
609640 assertEquals("Failed to convert to a Calendar and back", date1, DateUtils.toCalendar(date1).getTime());
610641 try {
611642 DateUtils.toCalendar(null);
612643 fail("Expected NullPointerException to be thrown");
613 } catch(NullPointerException npe) {
644 } catch(final NullPointerException npe) {
614645 // expected
615646 }
616647 }
619650 /**
620651 * Tests various values with the round method
621652 */
653 @Test
622654 public void testRound() throws Exception {
623655 // tests for public static Date round(Date date, int field)
624656 assertEquals("round year-1 failed",
746778 try {
747779 DateUtils.round((Date) null, Calendar.SECOND);
748780 fail();
749 } catch (IllegalArgumentException ex) {}
781 } catch (final IllegalArgumentException ex) {}
750782 try {
751783 DateUtils.round((Calendar) null, Calendar.SECOND);
752784 fail();
753 } catch (IllegalArgumentException ex) {}
785 } catch (final IllegalArgumentException ex) {}
754786 try {
755787 DateUtils.round((Object) null, Calendar.SECOND);
756788 fail();
757 } catch (IllegalArgumentException ex) {}
789 } catch (final IllegalArgumentException ex) {}
758790 try {
759791 DateUtils.round("", Calendar.SECOND);
760792 fail();
761 } catch (ClassCastException ex) {}
793 } catch (final ClassCastException ex) {}
762794 try {
763795 DateUtils.round(date1, -9999);
764796 fail();
765 } catch(IllegalArgumentException ex) {}
797 } catch(final IllegalArgumentException ex) {}
766798
767799 assertEquals("round ampm-1 failed",
768800 dateTimeParser.parse("February 3, 2002 00:00:00.000"),
842874 * Tests the Changes Made by LANG-346 to the DateUtils.modify() private method invoked
843875 * by DateUtils.round().
844876 */
877 @Test
845878 public void testRoundLang346() throws Exception
846879 {
847880 TimeZone.setDefault(defaultZone);
848881 dateTimeParser.setTimeZone(defaultZone);
849 Calendar testCalendar = Calendar.getInstance();
882 final Calendar testCalendar = Calendar.getInstance();
850883 testCalendar.set(2007, 6, 2, 8, 8, 50);
851884 Date date = testCalendar.getTime();
852885 assertEquals("Minute Round Up Failed",
904937 /**
905938 * Tests various values with the trunc method
906939 */
940 @Test
907941 public void testTruncate() throws Exception {
908942 // tests public static Date truncate(Date date, int field)
909943 assertEquals("truncate year-1 failed",
10401074 try {
10411075 DateUtils.truncate((Date) null, Calendar.SECOND);
10421076 fail();
1043 } catch (IllegalArgumentException ex) {}
1077 } catch (final IllegalArgumentException ex) {}
10441078 try {
10451079 DateUtils.truncate((Calendar) null, Calendar.SECOND);
10461080 fail();
1047 } catch (IllegalArgumentException ex) {}
1081 } catch (final IllegalArgumentException ex) {}
10481082 try {
10491083 DateUtils.truncate((Object) null, Calendar.SECOND);
10501084 fail();
1051 } catch (IllegalArgumentException ex) {}
1085 } catch (final IllegalArgumentException ex) {}
10521086 try {
10531087 DateUtils.truncate("", Calendar.SECOND);
10541088 fail();
1055 } catch (ClassCastException ex) {}
1089 } catch (final ClassCastException ex) {}
10561090
10571091 // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560
10581092 // Test truncate across beginning of daylight saving time
10751109 dateTimeParser.setTimeZone(defaultZone);
10761110
10771111 // Bug 31395, large dates
1078 Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
1079 GregorianCalendar endCal = new GregorianCalendar();
1112 final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
1113 final GregorianCalendar endCal = new GregorianCalendar();
10801114 endCal.setTime(endOfTime);
10811115 try {
10821116 DateUtils.truncate(endCal, Calendar.DATE);
10831117 fail();
1084 } catch (ArithmeticException ex) {}
1118 } catch (final ArithmeticException ex) {}
10851119 endCal.set(Calendar.YEAR, 280000001);
10861120 try {
10871121 DateUtils.truncate(endCal, Calendar.DATE);
10881122 fail();
1089 } catch (ArithmeticException ex) {}
1123 } catch (final ArithmeticException ex) {}
10901124 endCal.set(Calendar.YEAR, 280000000);
1091 Calendar cal = DateUtils.truncate(endCal, Calendar.DATE);
1125 final Calendar cal = DateUtils.truncate(endCal, Calendar.DATE);
10921126 assertEquals(0, cal.get(Calendar.HOUR));
10931127 }
10941128
10971131 *
10981132 * see http://issues.apache.org/jira/browse/LANG-59
10991133 */
1134 @Test
11001135 public void testTruncateLang59() throws Exception {
11011136 if (!SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) {
11021137 this.warn("WARNING: Test for LANG-59 not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION);
11041139 }
11051140
11061141 // Set TimeZone to Mountain Time
1107 TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT");
1142 final TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT");
11081143 TimeZone.setDefault(MST_MDT);
1109 DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
1144 final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
11101145 format.setTimeZone(MST_MDT);
11111146
1112 Date oct31_01MDT = new Date(1099206000000L);
1113
1114 Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour
1115 Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes
1116 Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds
1117 Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds
1147 final Date oct31_01MDT = new Date(1099206000000L);
1148
1149 final Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour
1150 final Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes
1151 final Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds
1152 final Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds
11181153
11191154 assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT));
11201155 assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT));
11231158 assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT));
11241159
11251160 // ------- Demonstrate Problem -------
1126 Calendar gval = Calendar.getInstance();
1161 final Calendar gval = Calendar.getInstance();
11271162 gval.setTime(new Date(oct31_01MDT.getTime()));
11281163 gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value
11291164 assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L);
11721207 }
11731208
11741209 // http://issues.apache.org/jira/browse/LANG-530
1210 @Test
11751211 public void testLang530() throws ParseException {
1176 Date d = new Date();
1177 String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d);
1178 Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() });
1212 final Date d = new Date();
1213 final String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d);
1214 final Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() });
11791215 // the format loses milliseconds so have to reintroduce them
11801216 assertEquals("Date not equal to itself ISO formatted and parsed", d.getTime(), d2.getTime() + d.getTime() % 1000);
11811217 }
11831219 /**
11841220 * Tests various values with the ceiling method
11851221 */
1222 @Test
11861223 public void testCeil() throws Exception {
11871224 // test javadoc
11881225 assertEquals("ceiling javadoc-1 failed",
13311368 try {
13321369 DateUtils.ceiling((Date) null, Calendar.SECOND);
13331370 fail();
1334 } catch (IllegalArgumentException ex) {}
1371 } catch (final IllegalArgumentException ex) {}
13351372 try {
13361373 DateUtils.ceiling((Calendar) null, Calendar.SECOND);
13371374 fail();
1338 } catch (IllegalArgumentException ex) {}
1375 } catch (final IllegalArgumentException ex) {}
13391376 try {
13401377 DateUtils.ceiling((Object) null, Calendar.SECOND);
13411378 fail();
1342 } catch (IllegalArgumentException ex) {}
1379 } catch (final IllegalArgumentException ex) {}
13431380 try {
13441381 DateUtils.ceiling("", Calendar.SECOND);
13451382 fail();
1346 } catch (ClassCastException ex) {}
1383 } catch (final ClassCastException ex) {}
13471384 try {
13481385 DateUtils.ceiling(date1, -9999);
13491386 fail();
1350 } catch(IllegalArgumentException ex) {}
1387 } catch(final IllegalArgumentException ex) {}
13511388
13521389
13531390 // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560
14121449 dateTimeParser.setTimeZone(defaultZone);
14131450
14141451 // Bug 31395, large dates
1415 Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
1416 GregorianCalendar endCal = new GregorianCalendar();
1452 final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
1453 final GregorianCalendar endCal = new GregorianCalendar();
14171454 endCal.setTime(endOfTime);
14181455 try {
14191456 DateUtils.ceiling(endCal, Calendar.DATE);
14201457 fail();
1421 } catch (ArithmeticException ex) {}
1458 } catch (final ArithmeticException ex) {}
14221459 endCal.set(Calendar.YEAR, 280000001);
14231460 try {
14241461 DateUtils.ceiling(endCal, Calendar.DATE);
14251462 fail();
1426 } catch (ArithmeticException ex) {}
1463 } catch (final ArithmeticException ex) {}
14271464 endCal.set(Calendar.YEAR, 280000000);
1428 Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE);
1465 final Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE);
14291466 assertEquals(0, cal.get(Calendar.HOUR));
14301467 }
14311468
14321469 /**
14331470 * Tests the iterator exceptions
14341471 */
1472 @Test
14351473 public void testIteratorEx() throws Exception {
14361474 try {
14371475 DateUtils.iterator(Calendar.getInstance(), -9999);
1438 } catch (IllegalArgumentException ex) {}
1476 } catch (final IllegalArgumentException ex) {}
14391477 try {
14401478 DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER);
14411479 fail();
1442 } catch (IllegalArgumentException ex) {}
1480 } catch (final IllegalArgumentException ex) {}
14431481 try {
14441482 DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER);
14451483 fail();
1446 } catch (IllegalArgumentException ex) {}
1484 } catch (final IllegalArgumentException ex) {}
14471485 try {
14481486 DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER);
14491487 fail();
1450 } catch (IllegalArgumentException ex) {}
1488 } catch (final IllegalArgumentException ex) {}
14511489 try {
14521490 DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER);
14531491 fail();
1454 } catch (ClassCastException ex) {}
1492 } catch (final ClassCastException ex) {}
14551493 }
14561494
14571495 /**
14581496 * Tests the calendar iterator for week ranges
14591497 */
1498 @Test
14601499 public void testWeekIterator() throws Exception {
1461 Calendar now = Calendar.getInstance();
1500 final Calendar now = Calendar.getInstance();
14621501 for (int i = 0; i< 7; i++) {
1463 Calendar today = DateUtils.truncate(now, Calendar.DATE);
1464 Calendar sunday = DateUtils.truncate(now, Calendar.DATE);
1502 final Calendar today = DateUtils.truncate(now, Calendar.DATE);
1503 final Calendar sunday = DateUtils.truncate(now, Calendar.DATE);
14651504 sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK));
1466 Calendar monday = DateUtils.truncate(now, Calendar.DATE);
1505 final Calendar monday = DateUtils.truncate(now, Calendar.DATE);
14671506 if (monday.get(Calendar.DAY_OF_WEEK) == 1) {
14681507 //This is sunday... roll back 6 days
14691508 monday.add(Calendar.DATE, -6);
14701509 } else {
14711510 monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK));
14721511 }
1473 Calendar centered = DateUtils.truncate(now, Calendar.DATE);
1512 final Calendar centered = DateUtils.truncate(now, Calendar.DATE);
14741513 centered.add(Calendar.DATE, -3);
14751514
14761515 Iterator<?> it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_SUNDAY);
14891528 try {
14901529 it.next();
14911530 fail();
1492 } catch (NoSuchElementException ex) {}
1531 } catch (final NoSuchElementException ex) {}
14931532 it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER);
14941533 it.next();
14951534 try {
14961535 it.remove();
1497 } catch( UnsupportedOperationException ex) {}
1536 } catch( final UnsupportedOperationException ex) {}
14981537
14991538 now.add(Calendar.DATE,1);
15001539 }
15031542 /**
15041543 * Tests the calendar iterator for month-based ranges
15051544 */
1545 @Test
15061546 public void testMonthIterator() throws Exception {
15071547 Iterator<?> it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY);
15081548 assertWeekIterator(it,
15251565 dateParser.parse("December 2, 2001"));
15261566 }
15271567
1568 @Test
1569 public void testLANG799_EN_OK() throws ParseException {
1570 final Locale dflt = Locale.getDefault();
1571 Locale.setDefault(Locale.ENGLISH);
1572 try {
1573 DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1574 DateUtils.parseDateStrictly("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1575 } finally {
1576 Locale.setDefault(dflt);
1577 }
1578 }
1579
1580 // Parse German date with English Locale
1581 @Test(expected=ParseException.class)
1582 public void testLANG799_EN_FAIL() throws ParseException {
1583 final Locale dflt = Locale.getDefault();
1584 Locale.setDefault(Locale.ENGLISH);
1585 try {
1586 DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1587 } finally {
1588 Locale.setDefault(dflt);
1589 }
1590 }
1591
1592 @Test
1593 public void testLANG799_DE_OK() throws ParseException {
1594 final Locale dflt = Locale.getDefault();
1595 Locale.setDefault(Locale.GERMAN);
1596 try {
1597 DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1598 DateUtils.parseDateStrictly("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1599 } finally {
1600 Locale.setDefault(dflt);
1601 }
1602 }
1603
1604 // Parse English date with German Locale
1605 @Test(expected=ParseException.class)
1606 public void testLANG799_DE_FAIL() throws ParseException {
1607 final Locale dflt = Locale.getDefault();
1608 Locale.setDefault(Locale.GERMAN);
1609 try {
1610 DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1611 } finally {
1612 Locale.setDefault(dflt);
1613 }
1614 }
1615
1616 // Parse German date with English Locale, specifying German Locale override
1617 @Test
1618 public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException {
1619 final Locale dflt = Locale.getDefault();
1620 Locale.setDefault(Locale.ENGLISH);
1621 try {
1622 DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", Locale.GERMAN, "EEE, dd MMM yyyy HH:mm:ss zzz");
1623 } finally {
1624 Locale.setDefault(dflt);
1625 }
1626 }
1627
15281628 /**
15291629 * This checks that this is a 7 element iterator of Calendar objects
15301630 * that are dates (no time), and exactly 1 day spaced after each other.
15311631 */
1532 private static void assertWeekIterator(Iterator<?> it, Calendar start) {
1533 Calendar end = (Calendar) start.clone();
1632 private static void assertWeekIterator(final Iterator<?> it, final Calendar start) {
1633 final Calendar end = (Calendar) start.clone();
15341634 end.add(Calendar.DATE, 6);
15351635
15361636 assertWeekIterator(it, start, end);
15391639 /**
15401640 * Convenience method for when working with Date objects
15411641 */
1542 private static void assertWeekIterator(Iterator<?> it, Date start, Date end) {
1543 Calendar calStart = Calendar.getInstance();
1642 private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end) {
1643 final Calendar calStart = Calendar.getInstance();
15441644 calStart.setTime(start);
1545 Calendar calEnd = Calendar.getInstance();
1645 final Calendar calEnd = Calendar.getInstance();
15461646 calEnd.setTime(end);
15471647
15481648 assertWeekIterator(it, calStart, calEnd);
15531653 * that are dates (no time), and exactly 1 day spaced after each other
15541654 * (in addition to the proper start and stop dates)
15551655 */
1556 private static void assertWeekIterator(Iterator<?> it, Calendar start, Calendar end) {
1656 private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end) {
15571657 Calendar cal = (Calendar) it.next();
1558 assertEquals("", start, cal, 0);
1658 assertCalendarsEquals("", start, cal, 0);
15591659 Calendar last = null;
15601660 int count = 1;
15611661 while (it.hasNext()) {
15621662 //Check this is just a date (no time component)
1563 assertEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0);
1663 assertCalendarsEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0);
15641664
15651665 last = cal;
15661666 cal = (Calendar) it.next();
15681668
15691669 //Check that this is one day more than the last date
15701670 last.add(Calendar.DATE, 1);
1571 assertEquals("", last, cal, 0);
1671 assertCalendarsEquals("", last, cal, 0);
15721672 }
15731673 if (count % 7 != 0) {
15741674 throw new AssertionFailedError("There were " + count + " days in this iterator");
15751675 }
1576 assertEquals("", end, cal, 0);
1676 assertCalendarsEquals("", end, cal, 0);
15771677 }
15781678
15791679 /**
15801680 * Used to check that Calendar objects are close enough
15811681 * delta is in milliseconds
15821682 */
1583 private static void assertEquals(String message, Calendar cal1, Calendar cal2, long delta) {
1683 private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta) {
15841684 if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) {
15851685 throw new AssertionFailedError(
15861686 message + " expected " + cal1.getTime() + " but got " + cal2.getTime());
15871687 }
15881688 }
15891689
1590 void warn(String msg) {
1690 void warn(final String msg) {
15911691 System.err.println(msg);
15921692 }
15931693 }
1616
1717 package org.apache.commons.lang3.time;
1818
19 import org.junit.Test;
20 import static org.junit.Assert.*;
1921 import java.lang.reflect.Constructor;
2022 import java.lang.reflect.Modifier;
2123 import java.util.Calendar;
2224 import java.util.TimeZone;
2325
24 import junit.framework.TestCase;
25
2626 /**
2727 * TestCase for DurationFormatUtils.
2828 *
2929 */
30 public class DurationFormatUtilsTest extends TestCase {
31
32 public DurationFormatUtilsTest(String s) {
33 super(s);
34 }
30 public class DurationFormatUtilsTest {
3531
3632 // -----------------------------------------------------------------------
33 @Test
3734 public void testConstructor() {
3835 assertNotNull(new DurationFormatUtils());
39 Constructor<?>[] cons = DurationFormatUtils.class.getDeclaredConstructors();
36 final Constructor<?>[] cons = DurationFormatUtils.class.getDeclaredConstructors();
4037 assertEquals(1, cons.length);
41 assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
42 assertEquals(true, Modifier.isPublic(DurationFormatUtils.class.getModifiers()));
43 assertEquals(false, Modifier.isFinal(DurationFormatUtils.class.getModifiers()));
38 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
39 assertTrue(Modifier.isPublic(DurationFormatUtils.class.getModifiers()));
40 assertFalse(Modifier.isFinal(DurationFormatUtils.class.getModifiers()));
4441 }
4542
4643 // -----------------------------------------------------------------------
44 @Test
4745 public void testFormatDurationWords() {
4846 String text = null;
4947
131129 /**
132130 * Tests that "1 <unit>s" gets converted to "1 <unit>" but that "11 <unit>s" is left alone.
133131 */
132 @Test
134133 public void testFormatDurationPluralWords() {
135 long oneSecond = 1000;
136 long oneMinute = oneSecond * 60;
137 long oneHour = oneMinute * 60;
138 long oneDay = oneHour * 24;
134 final long oneSecond = 1000;
135 final long oneMinute = oneSecond * 60;
136 final long oneHour = oneMinute * 60;
137 final long oneDay = oneHour * 24;
139138 String text = null;
140139
141140 text = DurationFormatUtils.formatDurationWords(oneSecond, false, false);
173172 assertEquals("1 day 1 hour 1 minute 1 second", text);
174173 }
175174
175 @Test
176176 public void testFormatDurationHMS() {
177177 long time = 0;
178178 assertEquals("0:00:00.000", DurationFormatUtils.formatDurationHMS(time));
202202 assertEquals("1:02:12.789", DurationFormatUtils.formatDurationHMS(time));
203203 }
204204
205 @Test
205206 public void testFormatDurationISO() {
206207 assertEquals("P0Y0M0DT0H0M0.000S", DurationFormatUtils.formatDurationISO(0L));
207208 assertEquals("P0Y0M0DT0H0M0.001S", DurationFormatUtils.formatDurationISO(1L));
210211 assertEquals("P0Y0M0DT0H1M15.321S", DurationFormatUtils.formatDurationISO(75321L));
211212 }
212213
214 @Test
213215 public void testFormatDuration() {
214216 long duration = 0;
215217 assertEquals("0", DurationFormatUtils.formatDuration(duration, "y"));
233235 assertEquals("60000", DurationFormatUtils.formatDuration(duration, "S"));
234236 assertEquals("01:00", DurationFormatUtils.formatDuration(duration, "mm:ss"));
235237
236 Calendar base = Calendar.getInstance();
238 final Calendar base = Calendar.getInstance();
237239 base.set(2000, 0, 1, 0, 0, 0);
238240 base.set(Calendar.MILLISECOND, 0);
239241
240 Calendar cal = Calendar.getInstance();
242 final Calendar cal = Calendar.getInstance();
241243 cal.set(2003, 1, 1, 0, 0, 0);
242244 cal.set(Calendar.MILLISECOND, 0);
243245 duration = cal.getTime().getTime() - base.getTime().getTime(); // duration from 2000-01-01 to cal
244246 // don't use 1970 in test as time zones were less reliable in 1970 than now
245247 // remember that duration formatting ignores time zones, working on strict hour lengths
246 int days = 366 + 365 + 365 + 31;
248 final int days = 366 + 365 + 365 + 31;
247249 assertEquals("0 0 " + days, DurationFormatUtils.formatDuration(duration, "y M d"));
248250 }
249251
252 @Test
250253 public void testFormatPeriodISO() {
251 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
252 Calendar base = Calendar.getInstance(timeZone);
254 final TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
255 final Calendar base = Calendar.getInstance(timeZone);
253256 base.set(1970, 0, 1, 0, 0, 0);
254257 base.set(Calendar.MILLISECOND, 0);
255258
256 Calendar cal = Calendar.getInstance(timeZone);
259 final Calendar cal = Calendar.getInstance(timeZone);
257260 cal.set(2002, 1, 23, 9, 11, 12);
258261 cal.set(Calendar.MILLISECOND, 1);
259262 String text;
274277 // assertEquals("P1Y2M3DT10H30M", text);
275278 }
276279
280 @Test
277281 public void testFormatPeriod() {
278 Calendar cal1970 = Calendar.getInstance();
282 final Calendar cal1970 = Calendar.getInstance();
279283 cal1970.set(1970, 0, 1, 0, 0, 0);
280284 cal1970.set(Calendar.MILLISECOND, 0);
281 long time1970 = cal1970.getTime().getTime();
285 final long time1970 = cal1970.getTime().getTime();
282286
283287 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "y"));
284288 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "M"));
301305 assertEquals("60000", DurationFormatUtils.formatPeriod(time1970, time, "S"));
302306 assertEquals("01:00", DurationFormatUtils.formatPeriod(time1970, time, "mm:ss"));
303307
304 Calendar cal = Calendar.getInstance();
308 final Calendar cal = Calendar.getInstance();
305309 cal.set(1973, 6, 1, 0, 0, 0);
306310 cal.set(Calendar.MILLISECOND, 0);
307311 time = cal.getTime().getTime();
327331 assertEquals("048", DurationFormatUtils.formatPeriod(time1970, time, "MMM"));
328332 }
329333
334 @Test
330335 public void testLexx() {
331336 // tests each constant
332337 assertArrayEquals(new DurationFormatUtils.Token[]{
341346 // tests the ISO8601-like
342347 assertArrayEquals(new DurationFormatUtils.Token[]{
343348 new DurationFormatUtils.Token(DurationFormatUtils.H, 1),
344 new DurationFormatUtils.Token(new StringBuffer(":"), 1),
349 new DurationFormatUtils.Token(new StringBuilder(":"), 1),
345350 new DurationFormatUtils.Token(DurationFormatUtils.m, 2),
346 new DurationFormatUtils.Token(new StringBuffer(":"), 1),
351 new DurationFormatUtils.Token(new StringBuilder(":"), 1),
347352 new DurationFormatUtils.Token(DurationFormatUtils.s, 2),
348 new DurationFormatUtils.Token(new StringBuffer("."), 1),
353 new DurationFormatUtils.Token(new StringBuilder("."), 1),
349354 new DurationFormatUtils.Token(DurationFormatUtils.S, 3)}, DurationFormatUtils.lexx("H:mm:ss.SSS"));
350355
351356 // test the iso extended format
352357 assertArrayEquals(new DurationFormatUtils.Token[]{
353 new DurationFormatUtils.Token(new StringBuffer("P"), 1),
358 new DurationFormatUtils.Token(new StringBuilder("P"), 1),
354359 new DurationFormatUtils.Token(DurationFormatUtils.y, 4),
355 new DurationFormatUtils.Token(new StringBuffer("Y"), 1),
360 new DurationFormatUtils.Token(new StringBuilder("Y"), 1),
356361 new DurationFormatUtils.Token(DurationFormatUtils.M, 1),
357 new DurationFormatUtils.Token(new StringBuffer("M"), 1),
362 new DurationFormatUtils.Token(new StringBuilder("M"), 1),
358363 new DurationFormatUtils.Token(DurationFormatUtils.d, 1),
359 new DurationFormatUtils.Token(new StringBuffer("DT"), 1),
364 new DurationFormatUtils.Token(new StringBuilder("DT"), 1),
360365 new DurationFormatUtils.Token(DurationFormatUtils.H, 1),
361 new DurationFormatUtils.Token(new StringBuffer("H"), 1),
366 new DurationFormatUtils.Token(new StringBuilder("H"), 1),
362367 new DurationFormatUtils.Token(DurationFormatUtils.m, 1),
363 new DurationFormatUtils.Token(new StringBuffer("M"), 1),
368 new DurationFormatUtils.Token(new StringBuilder("M"), 1),
364369 new DurationFormatUtils.Token(DurationFormatUtils.s, 1),
365 new DurationFormatUtils.Token(new StringBuffer("."), 1),
370 new DurationFormatUtils.Token(new StringBuilder("."), 1),
366371 new DurationFormatUtils.Token(DurationFormatUtils.S, 1),
367 new DurationFormatUtils.Token(new StringBuffer("S"), 1)}, DurationFormatUtils
372 new DurationFormatUtils.Token(new StringBuilder("S"), 1)}, DurationFormatUtils
368373 .lexx(DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN));
369374
370375 // test failures in equals
371 DurationFormatUtils.Token token = new DurationFormatUtils.Token(DurationFormatUtils.y, 4);
376 final DurationFormatUtils.Token token = new DurationFormatUtils.Token(DurationFormatUtils.y, 4);
372377 assertFalse("Token equal to non-Token class. ", token.equals(new Object()));
373378 assertFalse("Token equal to Token with wrong value class. ", token.equals(new DurationFormatUtils.Token(
374379 new Object())));
375380 assertFalse("Token equal to Token with different count. ", token.equals(new DurationFormatUtils.Token(
376381 DurationFormatUtils.y, 1)));
377 DurationFormatUtils.Token numToken = new DurationFormatUtils.Token(Integer.valueOf(1), 4);
382 final DurationFormatUtils.Token numToken = new DurationFormatUtils.Token(Integer.valueOf(1), 4);
378383 assertTrue("Token with Number value not equal to itself. ", numToken.equals(numToken));
379384 }
380385
381386
382387 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38401
388 @Test
383389 public void testBugzilla38401() {
384390 assertEqualDuration( "0000/00/30 16:00:00 000", new int[] { 2006, 0, 26, 18, 47, 34 },
385391 new int[] { 2006, 1, 26, 10, 47, 34 }, "yyyy/MM/dd HH:mm:ss SSS");
386392 }
387393
388394 // https://issues.apache.org/jira/browse/LANG-281
395 @Test
389396 public void testJiraLang281() {
390397 assertEqualDuration( "09", new int[] { 2005, 11, 31, 0, 0, 0 },
391398 new int[] { 2006, 9, 6, 0, 0, 0 }, "MM");
392399 }
393
400
401 @Test
402 public void testLANG815() {
403 final Calendar calendar = Calendar.getInstance();
404 calendar.set(2012, 6, 30, 0, 0, 0);
405 final long startMillis = calendar.getTimeInMillis();
406
407 calendar.set(2012, 8, 8);
408 final long endMillis = calendar.getTimeInMillis();
409
410 assertEquals("1 9", DurationFormatUtils.formatPeriod(startMillis, endMillis, "M d"));
411 }
412
394413 // Testing the under a day range in DurationFormatUtils.formatPeriod
414 @Test
395415 public void testLowDurations() {
396416 for(int hr=0; hr < 24; hr++) {
397417 for(int min=0; min < 60; min++) {
407427 }
408428
409429 // Attempting to test edge cases in DurationFormatUtils.formatPeriod
430 @Test
410431 public void testEdgeDurations() {
411432 assertEqualDuration( "01", new int[] { 2006, 0, 15, 0, 0, 0 },
412433 new int[] { 2006, 2, 10, 0, 0, 0 }, "MM");
496517
497518 }
498519
520 @Test
499521 public void testDurationsByBruteForce() {
500522 bruteForce(2006, 0, 1, "d", Calendar.DAY_OF_MONTH);
501523 bruteForce(2006, 0, 2, "d", Calendar.DAY_OF_MONTH);
519541 // }
520542 // }
521543
522 private void bruteForce(int year, int month, int day, String format, int calendarType) {
523 String msg = year + "-" + month + "-" + day + " to ";
524 Calendar c = Calendar.getInstance();
544 private void bruteForce(final int year, final int month, final int day, final String format, final int calendarType) {
545 final String msg = year + "-" + month + "-" + day + " to ";
546 final Calendar c = Calendar.getInstance();
525547 c.set(year, month, day, 0, 0, 0);
526 int[] array1 = new int[] { year, month, day, 0, 0, 0 };
527 int[] array2 = new int[] { year, month, day, 0, 0, 0 };
548 final int[] array1 = new int[] { year, month, day, 0, 0, 0 };
549 final int[] array2 = new int[] { year, month, day, 0, 0, 0 };
528550 for (int i=0; i < FOUR_YEARS; i++) {
529551 array2[0] = c.get(Calendar.YEAR);
530552 array2[1] = c.get(Calendar.MONTH);
531553 array2[2] = c.get(Calendar.DAY_OF_MONTH);
532 String tmpMsg = msg + array2[0] + "-" + array2[1] + "-" + array2[2] + " at ";
554 final String tmpMsg = msg + array2[0] + "-" + array2[1] + "-" + array2[2] + " at ";
533555 assertEqualDuration( tmpMsg + i, Integer.toString(i), array1, array2, format );
534556 c.add(calendarType, 1);
535557 }
536558 }
537559
538 private void assertEqualDuration(String expected, int[] start, int[] end, String format) {
560 private void assertEqualDuration(final String expected, final int[] start, final int[] end, final String format) {
539561 assertEqualDuration(null, expected, start, end, format);
540562 }
541 private void assertEqualDuration(String message, String expected, int[] start, int[] end, String format) {
542 Calendar cal1 = Calendar.getInstance();
563 private void assertEqualDuration(final String message, final String expected, final int[] start, final int[] end, final String format) {
564 final Calendar cal1 = Calendar.getInstance();
543565 cal1.set(start[0], start[1], start[2], start[3], start[4], start[5]);
544566 cal1.set(Calendar.MILLISECOND, 0);
545 Calendar cal2 = Calendar.getInstance();
567 final Calendar cal2 = Calendar.getInstance();
546568 cal2.set(end[0], end[1], end[2], end[3], end[4], end[5]);
547569 cal2.set(Calendar.MILLISECOND, 0);
548 long milli1 = cal1.getTime().getTime();
549 long milli2 = cal2.getTime().getTime();
550 String result = DurationFormatUtils.formatPeriod(milli1, milli2, format);
570 final long milli1 = cal1.getTime().getTime();
571 final long milli2 = cal2.getTime().getTime();
572 final String result = DurationFormatUtils.formatPeriod(milli1, milli2, format);
551573 if (message == null) {
552574 assertEquals(expected, result);
553575 } else {
555577 }
556578 }
557579
558 private void assertArrayEquals(DurationFormatUtils.Token[] obj1, DurationFormatUtils.Token[] obj2) {
580 private void assertArrayEquals(final DurationFormatUtils.Token[] obj1, final DurationFormatUtils.Token[] obj2) {
559581 assertEquals("Arrays are unequal length. ", obj1.length, obj2.length);
560582 for (int i = 0; i < obj1.length; i++) {
561583 assertTrue("Index " + i + " not equal, " + obj1[i] + " vs " + obj2[i], obj1[i].equals(obj2[i]));
1515 */
1616 package org.apache.commons.lang3.time;
1717
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertSame;
21 import static org.junit.Assert.assertTrue;
22 import static org.junit.Assert.fail;
23
24 import java.text.Format;
25 import java.text.ParseException;
1826 import java.text.SimpleDateFormat;
19 import java.util.Calendar;
2027 import java.util.Date;
21 import java.util.GregorianCalendar;
2228 import java.util.Locale;
2329 import java.util.TimeZone;
24
25 import junit.framework.TestCase;
26
27 import org.apache.commons.lang3.SerializationUtils;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.atomic.AtomicInteger;
34 import java.util.concurrent.atomic.AtomicLong;
35
36 import org.junit.Test;
2837
2938 /**
3039 * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}.
3140 *
3241 * @since 2.0
33 * @version $Id: FastDateFormatTest.java 1146138 2011-07-13 17:01:37Z joehni $
42 * @version $Id: FastDateFormatTest.java 1533544 2013-10-18 16:39:05Z sebb $
3443 */
35 public class FastDateFormatTest extends TestCase {
36
37 public FastDateFormatTest(String name) {
38 super(name);
39 }
40
44 public class FastDateFormatTest {
45
46 /*
47 * Only the cache methods need to be tested here.
48 * The print methods are tested by {@link FastDateFormat_PrinterTest}
49 * and the parse methods are tested by {@link FastDateFormat_ParserTest}
50 */
51 @Test
4152 public void test_getInstance() {
42 FastDateFormat format1 = FastDateFormat.getInstance();
43 FastDateFormat format2 = FastDateFormat.getInstance();
53 final FastDateFormat format1 = FastDateFormat.getInstance();
54 final FastDateFormat format2 = FastDateFormat.getInstance();
4455 assertSame(format1, format2);
45 assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern());
46 }
47
56 }
57
58 @Test
4859 public void test_getInstance_String() {
49 FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy");
50 FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy");
51 FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy");
60 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy");
61 final FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy");
62 final FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy");
5263
5364 assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
5465 assertSame(format2, format3);
5768 assertEquals(TimeZone.getDefault(), format2.getTimeZone());
5869 }
5970
71 @Test
6072 public void test_getInstance_String_TimeZone() {
61 Locale realDefaultLocale = Locale.getDefault();
62 TimeZone realDefaultZone = TimeZone.getDefault();
73 final Locale realDefaultLocale = Locale.getDefault();
74 final TimeZone realDefaultZone = TimeZone.getDefault();
6375 try {
6476 Locale.setDefault(Locale.US);
6577 TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
6678
67 FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
79 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
6880 TimeZone.getTimeZone("Atlantic/Reykjavik"));
69 FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
70 FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
71 FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
72 FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
73 FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");
81 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
82 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
83 final FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
84 final FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
85 final FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");
7486
7587 assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
7688 assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
8597 }
8698 }
8799
100 @Test
88101 public void test_getInstance_String_Locale() {
89 Locale realDefaultLocale = Locale.getDefault();
90 try {
91 Locale.setDefault(Locale.US);
92 FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
93 FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
94 FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
102 final Locale realDefaultLocale = Locale.getDefault();
103 try {
104 Locale.setDefault(Locale.US);
105 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
106 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
107 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
95108
96109 assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
97110 assertSame(format1, format3);
102115 }
103116 }
104117
118 @Test
105119 public void test_changeDefault_Locale_DateInstance() {
106 Locale realDefaultLocale = Locale.getDefault();
107 try {
108 Locale.setDefault(Locale.US);
109 FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY);
110 FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
120 final Locale realDefaultLocale = Locale.getDefault();
121 try {
122 Locale.setDefault(Locale.US);
123 final FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY);
124 final FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
111125 Locale.setDefault(Locale.GERMANY);
112 FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
126 final FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
113127
114128 assertSame(Locale.GERMANY, format1.getLocale());
115129 assertSame(Locale.US, format2.getLocale());
122136 }
123137 }
124138
139 @Test
125140 public void test_changeDefault_Locale_DateTimeInstance() {
126 Locale realDefaultLocale = Locale.getDefault();
127 try {
128 Locale.setDefault(Locale.US);
129 FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY);
130 FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
141 final Locale realDefaultLocale = Locale.getDefault();
142 try {
143 Locale.setDefault(Locale.US);
144 final FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY);
145 final FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
131146 Locale.setDefault(Locale.GERMANY);
132 FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
147 final FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
133148
134149 assertSame(Locale.GERMANY, format1.getLocale());
135150 assertSame(Locale.US, format2.getLocale());
142157 }
143158 }
144159
160 @Test
145161 public void test_getInstance_String_TimeZone_Locale() {
146 Locale realDefaultLocale = Locale.getDefault();
147 TimeZone realDefaultZone = TimeZone.getDefault();
162 final Locale realDefaultLocale = Locale.getDefault();
163 final TimeZone realDefaultZone = TimeZone.getDefault();
148164 try {
149165 Locale.setDefault(Locale.US);
150166 TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
151167
152 FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
168 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
153169 TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY);
154 FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
155 FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
170 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
171 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
156172 TimeZone.getDefault(), Locale.GERMANY);
157173
158174 assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2);
167183 Locale.setDefault(realDefaultLocale);
168184 TimeZone.setDefault(realDefaultZone);
169185 }
170 }
171
172 public void testFormat() {
173 Locale realDefaultLocale = Locale.getDefault();
174 TimeZone realDefaultZone = TimeZone.getDefault();
175 try {
176 Locale.setDefault(Locale.US);
177 TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
178
179 GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20);
180 GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00);
181 Date date1 = cal1.getTime();
182 Date date2 = cal2.getTime();
183 long millis1 = date1.getTime();
184 long millis2 = date2.getTime();
185
186 FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss");
187 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
188 assertEquals(sdf.format(date1), fdf.format(date1));
189 assertEquals("2003-01-10T15:33:20", fdf.format(date1));
190 assertEquals("2003-01-10T15:33:20", fdf.format(cal1));
191 assertEquals("2003-01-10T15:33:20", fdf.format(millis1));
192 assertEquals("2003-07-10T09:00:00", fdf.format(date2));
193 assertEquals("2003-07-10T09:00:00", fdf.format(cal2));
194 assertEquals("2003-07-10T09:00:00", fdf.format(millis2));
195
196 fdf = FastDateFormat.getInstance("Z");
197 assertEquals("-0500", fdf.format(date1));
198 assertEquals("-0500", fdf.format(cal1));
199 assertEquals("-0500", fdf.format(millis1));
200
201 assertEquals("-0400", fdf.format(date2));
202 assertEquals("-0400", fdf.format(cal2));
203 assertEquals("-0400", fdf.format(millis2));
204
205 fdf = FastDateFormat.getInstance("ZZ");
206 assertEquals("-05:00", fdf.format(date1));
207 assertEquals("-05:00", fdf.format(cal1));
208 assertEquals("-05:00", fdf.format(millis1));
209
210 assertEquals("-04:00", fdf.format(date2));
211 assertEquals("-04:00", fdf.format(cal2));
212 assertEquals("-04:00", fdf.format(millis2));
213
214 String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" +
215 " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z";
216 fdf = FastDateFormat.getInstance(pattern);
217 sdf = new SimpleDateFormat(pattern);
218 // SDF bug fix starting with Java 7
219 assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1));
220 assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2));
221 } finally {
222 Locale.setDefault(realDefaultLocale);
223 TimeZone.setDefault(realDefaultZone);
224 }
225 }
226
227 /**
228 * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}.
229 */
230 public void testShortDateStyleWithLocales() {
231 Locale usLocale = Locale.US;
232 Locale swedishLocale = new Locale("sv", "SE");
233 Calendar cal = Calendar.getInstance();
234 cal.set(2004, 1, 3);
235 FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale);
236 assertEquals("2/3/04", fdf.format(cal));
237
238 fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale);
239 assertEquals("2004-02-03", fdf.format(cal));
240
241 }
242
243 /**
244 * Tests that pre-1000AD years get padded with yyyy
245 */
246 public void testLowYearPadding() {
247 Calendar cal = Calendar.getInstance();
248 FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD");
249
250 cal.set(1,0,1);
251 assertEquals("0001/01/01", format.format(cal));
252 cal.set(10,0,1);
253 assertEquals("0010/01/01", format.format(cal));
254 cal.set(100,0,1);
255 assertEquals("0100/01/01", format.format(cal));
256 cal.set(999,0,1);
257 assertEquals("0999/01/01", format.format(cal));
258 }
259 /**
260 * Show Bug #39410 is solved
261 */
262 public void testMilleniumBug() {
263 Calendar cal = Calendar.getInstance();
264 FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy");
265
266 cal.set(1000,0,1);
267 assertEquals("01.01.1000", format.format(cal));
268 }
269
270 /**
271 * testLowYearPadding showed that the date was buggy
272 * This test confirms it, getting 366 back as a date
273 */
274 public void testSimpleDate() {
275 Calendar cal = Calendar.getInstance();
276 FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd");
277
278 cal.set(2004,11,31);
279 assertEquals("2004/12/31", format.format(cal));
280 cal.set(999,11,31);
281 assertEquals("0999/12/31", format.format(cal));
282 cal.set(1,2,2);
283 assertEquals("0001/03/02", format.format(cal));
284 }
285
286 public void testLang303() {
287 Calendar cal = Calendar.getInstance();
288 cal.set(2004,11,31);
289
290 FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd");
291 String output = format.format(cal);
292
293 format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) );
294 assertEquals(output, format.format(cal));
295 }
296
297 public void testLang538() {
298 // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16)
299 // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone
300 GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
301 cal.clear();
302 cal.set(2009, 9, 16, 8, 42, 16);
303
304 FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
305 assertEquals("dateTime", "2009-10-16T16:42:16.000Z", format.format(cal.getTime()));
306 assertEquals("dateTime", "2009-10-16T08:42:16.000Z", format.format(cal));
307 }
308
309 public void testLang645() {
310 Locale locale = new Locale("sv", "SE");
311
312 Calendar cal = Calendar.getInstance();
313 cal.set(2010, 0, 1, 12, 0, 0);
314 Date d = cal.getTime();
315
316 FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale);
317
318 assertEquals("fredag, week 53", fdf.format(d));
186 }
187
188 @Test
189 public void testCheckDefaults() {
190 final FastDateFormat format = FastDateFormat.getInstance();
191 final FastDateFormat medium = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT);
192 assertEquals(medium, format);
193
194 final SimpleDateFormat sdf = new SimpleDateFormat();
195 assertEquals(sdf.toPattern(), format.getPattern());
196
197 assertEquals(Locale.getDefault(), format.getLocale());
198 assertEquals(TimeZone.getDefault(), format.getTimeZone());
199 }
200
201 @Test
202 public void testCheckDifferingStyles() {
203 final FastDateFormat shortShort = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT, Locale.US);
204 final FastDateFormat shortLong = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.LONG, Locale.US);
205 final FastDateFormat longShort = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.SHORT, Locale.US);
206 final FastDateFormat longLong = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.LONG, Locale.US);
207
208 assertFalse(shortShort.equals(shortLong));
209 assertFalse(shortShort.equals(longShort));
210 assertFalse(shortShort.equals(longLong));
211 assertFalse(shortLong.equals(longShort));
212 assertFalse(shortLong.equals(longLong));
213 assertFalse(longShort.equals(longLong));
214 }
215
216 @Test
217 public void testDateDefaults() {
218 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, Locale.CANADA),
219 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
220
221 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York")),
222 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
223
224 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG),
225 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
226 }
227
228 @Test
229 public void testTimeDefaults() {
230 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, Locale.CANADA),
231 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
232
233 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York")),
234 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
235
236 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG),
237 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
238 }
239
240 @Test
241 public void testTimeDateDefaults() {
242 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, Locale.CANADA),
243 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.CANADA));
244
245 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getTimeZone("America/New_York")),
246 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
247
248 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM),
249 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.getDefault()));
250 }
251
252 @Test
253 public void testParseSync() throws InterruptedException {
254 final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS Z";
255 final FastDateFormat formatter= FastDateFormat.getInstance(pattern);
256
257 final long sdfTime= measureTime(formatter, new SimpleDateFormat(pattern) {
258 private static final long serialVersionUID = 1L; // because SimpleDateFormat is serializable
259
260 @Override
261 public Object parseObject(final String formattedDate) throws ParseException {
262 synchronized(this) {
263 return super.parse(formattedDate);
264 }
265 }
266 });
267
268 final long fdfTime= measureTime(formatter, FastDateFormat.getInstance(pattern));
269
270 final String times= ">>FastDateFormatTest: FastDateParser:"+fdfTime+" SimpleDateFormat:"+sdfTime;
271 System.out.println(times);
272 }
273
274 final static private int NTHREADS= 10;
275 final static private int NROUNDS= 10000;
276
277 private long measureTime(final Format formatter, final Format parser) throws InterruptedException {
278 final ExecutorService pool = Executors.newFixedThreadPool(NTHREADS);
279 final AtomicInteger failures= new AtomicInteger(0);
280 final AtomicLong totalElapsed= new AtomicLong(0);
281
282 for(int i= 0; i<NTHREADS; ++i) {
283 pool.submit(new Runnable() {
284 @Override
285 public void run() {
286 for(int j= 0; j<NROUNDS; ++j) {
287 try {
288 final Date date= new Date();
289 final String formattedDate= formatter.format(date);
290 final long start= System.currentTimeMillis();
291 final Object pd= parser.parseObject(formattedDate);
292 totalElapsed.addAndGet(System.currentTimeMillis()-start);
293 if(!date.equals(pd)) {
294 failures.incrementAndGet();
295 }
296 } catch (final Exception e) {
297 failures.incrementAndGet();
298 e.printStackTrace();
299 }
300 }
301 }
302 });
303 }
304 pool.shutdown();
305 if(!pool.awaitTermination(20, TimeUnit.SECONDS)) {
306 pool.shutdownNow();
307 fail("did not complete tasks");
308 }
309 assertEquals(0, failures.get());
310 return totalElapsed.get();
319311 }
320312 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import java.util.Locale;
19 import java.util.TimeZone;
20
21 /**
22 * Unit tests for the parse methods of FastDateFormat
23 *
24 * @since 3.2
25 */
26 public class FastDateFormat_ParserTest extends FastDateParserTest {
27
28 @Override
29 protected DateParser getInstance(final String format, final TimeZone timeZone, final Locale locale) {
30 return FastDateFormat.getInstance(format, timeZone, locale);
31 }
32 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import java.util.Locale;
19 import java.util.TimeZone;
20
21 /**
22 * Unit tests for the print methods of FastDateFormat
23 *
24 * @since 3.2
25 */
26 public class FastDateFormat_PrinterTest extends FastDatePrinterTest {
27
28 @Override
29 protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale) {
30 return FastDateFormat.getInstance(format, timeZone, locale);
31 }
32 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional inparserion regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertTrue;
21 import java.io.Serializable;
22 import java.text.ParseException;
23 import java.text.SimpleDateFormat;
24 import java.util.Calendar;
25 import java.util.Date;
26 import java.util.GregorianCalendar;
27 import java.util.HashMap;
28 import java.util.Locale;
29 import java.util.Map;
30 import java.util.TimeZone;
31
32 import org.junit.Assert;
33
34 import org.apache.commons.lang3.SerializationUtils;
35 import org.junit.Test;
36
37 /**
38 * Unit tests {@link org.apache.commons.lang3.time.FastDateParser}.
39 *
40 * @version $Id: FastDateParserTest.java 1552661 2013-12-20 13:36:30Z britter $
41 * @since 3.2
42 */
43 public class FastDateParserTest {
44 private static final String SHORT_FORMAT_NOERA = "y/M/d/h/a/m/E/Z";
45 private static final String LONG_FORMAT_NOERA = "yyyy/MMMM/dddd/hhhh/mmmm/aaaa/EEEE/ZZZZ";
46 private static final String SHORT_FORMAT = "G/" + SHORT_FORMAT_NOERA;
47 private static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA;
48
49 private static final String yMdHmsSZ = "yyyy-MM-dd'T'HH:mm:ss.SSS Z";
50 private static final String DMY_DOT = "dd.MM.yyyy";
51 private static final String YMD_SLASH = "yyyy/MM/dd";
52 private static final String MDY_DASH = "MM-DD-yyyy";
53 private static final String MDY_SLASH = "MM/DD/yyyy";
54
55 private static final TimeZone REYKJAVIK = TimeZone.getTimeZone("Atlantic/Reykjavik");
56 private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
57 private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
58
59 private static final Locale SWEDEN = new Locale("sv", "SE");
60
61 DateParser getInstance(final String format) {
62 return getInstance(format, TimeZone.getDefault(), Locale.getDefault());
63 }
64
65 private DateParser getDateInstance(final int dateStyle, final Locale locale) {
66 return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault());
67 }
68
69 private DateParser getInstance(final String format, final Locale locale) {
70 return getInstance(format, TimeZone.getDefault(), locale);
71 }
72
73 private DateParser getInstance(final String format, final TimeZone timeZone) {
74 return getInstance(format, timeZone, Locale.getDefault());
75 }
76
77 /**
78 * Override this method in derived tests to change the construction of instances
79 */
80 protected DateParser getInstance(final String format, final TimeZone timeZone, final Locale locale) {
81 return new FastDateParser(format, timeZone, locale);
82 }
83
84 @Test
85 public void test_Equality_Hash() {
86 final DateParser[] parsers= {
87 getInstance(yMdHmsSZ, NEW_YORK, Locale.US),
88 getInstance(DMY_DOT, NEW_YORK, Locale.US),
89 getInstance(YMD_SLASH, NEW_YORK, Locale.US),
90 getInstance(MDY_DASH, NEW_YORK, Locale.US),
91 getInstance(MDY_SLASH, NEW_YORK, Locale.US),
92 getInstance(MDY_SLASH, REYKJAVIK, Locale.US),
93 getInstance(MDY_SLASH, REYKJAVIK, SWEDEN)
94 };
95
96 final Map<DateParser,Integer> map= new HashMap<DateParser,Integer>();
97 int i= 0;
98 for(final DateParser parser:parsers) {
99 map.put(parser, Integer.valueOf(i++));
100 }
101
102 i= 0;
103 for(final DateParser parser:parsers) {
104 assertEquals(i++, map.get(parser).intValue());
105 }
106 }
107
108 @Test
109 public void testParseZone() throws ParseException {
110 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
111 cal.clear();
112 cal.set(2003, 6, 10, 16, 33, 20);
113
114 final DateParser fdf = getInstance(yMdHmsSZ, NEW_YORK, Locale.US);
115
116 assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 -0500"));
117 assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 GMT-05:00"));
118 assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 Eastern Daylight Time"));
119 assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 EDT"));
120
121 cal.setTimeZone(TimeZone.getTimeZone("GMT-3"));
122 cal.set(2003, 1, 10, 9, 0, 0);
123
124 assertEquals(cal.getTime(), fdf.parse("2003-02-10T09:00:00.000 -0300"));
125
126 cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
127 cal.set(2003, 1, 10, 15, 5, 6);
128
129 assertEquals(cal.getTime(), fdf.parse("2003-02-10T15:05:06.000 +0500"));
130 }
131
132 @Test
133 public void testParseLongShort() throws ParseException {
134 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
135 cal.clear();
136 cal.set(2003, 1, 10, 15, 33, 20);
137 cal.set(Calendar.MILLISECOND, 989);
138 cal.setTimeZone(NEW_YORK);
139
140 DateParser fdf = getInstance("yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK, Locale.US);
141
142 assertEquals(cal.getTime(), fdf.parse("2003 AD February 0010 PM Monday 0015 0033 0020 0989 GMT-05:00"));
143 cal.set(Calendar.ERA, GregorianCalendar.BC);
144
145 final Date parse = fdf.parse("2003 BC February 0010 PM Saturday 0015 0033 0020 0989 GMT-05:00");
146 assertEquals(cal.getTime(), parse);
147
148 fdf = getInstance("y G M d a E H m s S Z", NEW_YORK, Locale.US);
149 assertEquals(cal.getTime(), fdf.parse("03 BC 2 10 PM Sat 15 33 20 989 -0500"));
150
151 cal.set(Calendar.ERA, GregorianCalendar.AD);
152 assertEquals(cal.getTime(), fdf.parse("03 AD 2 10 PM Saturday 15 33 20 989 -0500"));
153 }
154
155 @Test
156 public void testAmPm() throws ParseException {
157 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
158 cal.clear();
159
160 final DateParser h = getInstance("yyyy-MM-dd hh a mm:ss", NEW_YORK, Locale.US);
161 final DateParser K = getInstance("yyyy-MM-dd KK a mm:ss", NEW_YORK, Locale.US);
162 final DateParser k = getInstance("yyyy-MM-dd kk:mm:ss", NEW_YORK, Locale.US);
163 final DateParser H = getInstance("yyyy-MM-dd HH:mm:ss", NEW_YORK, Locale.US);
164
165 cal.set(2010, 7, 1, 0, 33, 20);
166 assertEquals(cal.getTime(), h.parse("2010-08-01 12 AM 33:20"));
167 assertEquals(cal.getTime(), K.parse("2010-08-01 0 AM 33:20"));
168 assertEquals(cal.getTime(), k.parse("2010-08-01 00:33:20"));
169 assertEquals(cal.getTime(), H.parse("2010-08-01 00:33:20"));
170
171 cal.set(2010, 7, 1, 3, 33, 20);
172 assertEquals(cal.getTime(), h.parse("2010-08-01 3 AM 33:20"));
173 assertEquals(cal.getTime(), K.parse("2010-08-01 3 AM 33:20"));
174 assertEquals(cal.getTime(), k.parse("2010-08-01 03:33:20"));
175 assertEquals(cal.getTime(), H.parse("2010-08-01 03:33:20"));
176
177 cal.set(2010, 7, 1, 15, 33, 20);
178 assertEquals(cal.getTime(), h.parse("2010-08-01 3 PM 33:20"));
179 assertEquals(cal.getTime(), K.parse("2010-08-01 3 PM 33:20"));
180 assertEquals(cal.getTime(), k.parse("2010-08-01 15:33:20"));
181 assertEquals(cal.getTime(), H.parse("2010-08-01 15:33:20"));
182
183 cal.set(2010, 7, 1, 12, 33, 20);
184 assertEquals(cal.getTime(), h.parse("2010-08-01 12 PM 33:20"));
185 assertEquals(cal.getTime(), K.parse("2010-08-01 0 PM 33:20"));
186 assertEquals(cal.getTime(), k.parse("2010-08-01 12:33:20"));
187 assertEquals(cal.getTime(), H.parse("2010-08-01 12:33:20"));
188 }
189
190 @Test
191 // Check that all Locales can parse the formats we use
192 public void testParses() throws Exception {
193 for(final Locale locale : Locale.getAvailableLocales()) {
194 for(final TimeZone tz : new TimeZone[]{NEW_YORK, GMT}) {
195 final Calendar cal = Calendar.getInstance(tz);
196 for(final int year : new int[]{2003, 1940, 1868, 1867, 0, -1940}) {
197 // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/calendar.doc.html
198 if (year < 1868 && locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
199 continue; // Japanese imperial calendar does not support eras before 1868
200 }
201 cal.clear();
202 if (year < 0) {
203 cal.set(-year, 1, 10);
204 cal.set(Calendar.ERA, GregorianCalendar.BC);
205 } else {
206 cal.set(year, 1, 10);
207 }
208 final Date in = cal.getTime();
209 for(final String format : new String[]{LONG_FORMAT, SHORT_FORMAT}) {
210 final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
211 if (format.equals(SHORT_FORMAT)) {
212 if (year < 1930) {
213 sdf.set2DigitYearStart(cal.getTime());
214 }
215 }
216 final String fmt = sdf.format(in);
217 try {
218 final Date out = sdf.parse(fmt);
219
220 assertEquals(locale.toString()+" "+year+" "+ format+ " "+tz.getID(), in, out);
221 } catch (final ParseException pe) {
222 System.out.println(fmt+" "+locale.toString()+" "+year+" "+ format+ " "+tz.getID());
223 throw pe;
224 }
225 }
226 }
227 }
228 }
229 }
230
231 @Test
232 public void testLocales_Long_AD() throws Exception {
233 testLocales(LONG_FORMAT, false);
234 }
235
236 @Test
237 public void testLocales_Long_BC() throws Exception {
238 testLocales(LONG_FORMAT, true);
239 }
240
241 @Test
242 public void testLocales_Short_AD() throws Exception {
243 testLocales(SHORT_FORMAT, false);
244 }
245
246 @Test
247 public void testLocales_Short_BC() throws Exception {
248 testLocales(SHORT_FORMAT, true);
249 }
250
251 @Test
252 public void testLocales_LongNoEra_AD() throws Exception {
253 testLocales(LONG_FORMAT_NOERA, false);
254 }
255
256 @Test
257 public void testLocales_LongNoEra_BC() throws Exception {
258 testLocales(LONG_FORMAT_NOERA, true);
259 }
260
261 @Test
262 public void testLocales_ShortNoEra_AD() throws Exception {
263 testLocales(SHORT_FORMAT_NOERA, false);
264 }
265
266 @Test
267 public void testLocales_ShortNoEra_BC() throws Exception {
268 testLocales(SHORT_FORMAT_NOERA, true);
269 }
270
271 private void testLocales(final String format, final boolean eraBC) throws Exception {
272
273 final Calendar cal= Calendar.getInstance(GMT);
274 cal.clear();
275 cal.set(2003, 1, 10);
276 if (eraBC) {
277 cal.set(Calendar.ERA, GregorianCalendar.BC);
278 }
279 for(final Locale locale : Locale.getAvailableLocales()) {
280 // ja_JP_JP cannot handle dates before 1868 properly
281 if (eraBC && locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
282 continue;
283 }
284 final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
285 final DateParser fdf = getInstance(format, locale);
286
287 try {
288 checkParse(locale, cal, sdf, fdf);
289 } catch(final ParseException ex) {
290 Assert.fail("Locale "+locale+ " failed with "+format+" era "+(eraBC?"BC":"AD")+"\n" + trimMessage(ex.toString()));
291 }
292 }
293 }
294
295 private String trimMessage(final String msg) {
296 if (msg.length() < 100) {
297 return msg;
298 }
299 final int gmt = msg.indexOf("(GMT");
300 if (gmt > 0) {
301 return msg.substring(0, gmt+4)+"...)";
302 }
303 return msg.substring(0, 100)+"...";
304 }
305
306 private void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat sdf, final DateParser fdf) throws ParseException {
307 final String formattedDate= sdf.format(cal.getTime());
308 final Date expectedTime = sdf.parse(formattedDate);
309 final Date actualTime = fdf.parse(formattedDate);
310 assertEquals(locale.toString()+" "+formattedDate
311 +"\n",expectedTime, actualTime);
312 }
313
314 @Test
315 public void testParseNumerics() throws ParseException {
316 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
317 cal.clear();
318 cal.set(2003, 1, 10, 15, 33, 20);
319 cal.set(Calendar.MILLISECOND, 989);
320
321 final DateParser fdf = getInstance("yyyyMMddHHmmssSSS", NEW_YORK, Locale.US);
322 assertEquals(cal.getTime(), fdf.parse("20030210153320989"));
323 }
324
325 @Test
326 public void testQuotes() throws ParseException {
327 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
328 cal.clear();
329 cal.set(2003, 1, 10, 15, 33, 20);
330 cal.set(Calendar.MILLISECOND, 989);
331
332 final DateParser fdf = getInstance("''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US);
333 assertEquals(cal.getTime(), fdf.parse("'20030210A'B153320989'"));
334 }
335
336 @Test
337 public void testSpecialCharacters() throws Exception {
338 testSdfAndFdp("q" ,"", true); // bad pattern character (at present)
339 testSdfAndFdp("Q" ,"", true); // bad pattern character
340 testSdfAndFdp("$" ,"$", false); // OK
341 testSdfAndFdp("?.d" ,"?.12", false); // OK
342 testSdfAndFdp("''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK
343 testSdfAndFdp("''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK
344 testSdfAndFdp("'$\\Ed'" ,"$\\Ed", false); // OK
345 }
346
347 @Test
348 public void testLANG_832() throws Exception {
349 testSdfAndFdp("'d'd" ,"d3", false); // OK
350 testSdfAndFdp("'d'd'","d3", true); // should fail (unterminated quote)
351 }
352
353 @Test
354 public void testLANG_831() throws Exception {
355 testSdfAndFdp("M E","3 Tue", true);
356 }
357
358 private void testSdfAndFdp(final String format, final String date, final boolean shouldFail)
359 throws Exception {
360 final boolean debug = false;
361 Date dfdp = null;
362 Date dsdf = null;
363 Throwable f = null;
364 Throwable s = null;
365
366 try {
367 final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
368 sdf.setTimeZone(NEW_YORK);
369 dsdf = sdf.parse(date);
370 if (shouldFail) {
371 Assert.fail("Expected SDF failure, but got " + dsdf + " for ["+format+","+date+"]");
372 }
373 } catch (final Exception e) {
374 s = e;
375 if (!shouldFail) {
376 throw e;
377 }
378 if (debug) {
379 System.out.println("sdf:"+format+"/"+date+"=>"+e);
380 }
381 }
382
383 try {
384 final DateParser fdp = getInstance(format, NEW_YORK, Locale.US);
385 dfdp = fdp.parse(date);
386 if (shouldFail) {
387 Assert.fail("Expected FDF failure, but got " + dfdp + " for ["+format+","+date+"] using "+((FastDateParser)fdp).getParsePattern());
388 }
389 } catch (final Exception e) {
390 f = e;
391 if (!shouldFail) {
392 throw e;
393 }
394 if (debug) {
395 System.out.println("fdf:"+format+"/"+date+"=>"+e);
396 }
397 }
398 // SDF and FDF should produce equivalent results
399 assertTrue("Should both or neither throw Exceptions", (f==null)==(s==null));
400 assertEquals("Parsed dates should be equal", dsdf, dfdp);
401 if (debug) {
402 System.out.println(format + "," + date + " => " + dsdf);
403 }
404 }
405
406 @Test
407 public void testDayOf() throws ParseException {
408 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
409 cal.clear();
410 cal.set(2003, 1, 10);
411
412 final DateParser fdf = getInstance("W w F D y", NEW_YORK, Locale.US);
413 assertEquals(cal.getTime(), fdf.parse("3 7 2 41 03"));
414 }
415
416 /**
417 * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
418 * @throws ParseException
419 */
420 @Test
421 public void testShortDateStyleWithLocales() throws ParseException {
422 DateParser fdf = getDateInstance(FastDateFormat.SHORT, Locale.US);
423 final Calendar cal = Calendar.getInstance();
424 cal.clear();
425
426 cal.set(2004, 1, 3);
427 assertEquals(cal.getTime(), fdf.parse("2/3/04"));
428
429 fdf = getDateInstance(FastDateFormat.SHORT, SWEDEN);
430 assertEquals(cal.getTime(), fdf.parse("2004-02-03"));
431 }
432
433 /**
434 * Tests that pre-1000AD years get padded with yyyy
435 * @throws ParseException
436 */
437 @Test
438 public void testLowYearPadding() throws ParseException {
439 final DateParser parser = getInstance(YMD_SLASH);
440 final Calendar cal = Calendar.getInstance();
441 cal.clear();
442
443 cal.set(1,0,1);
444 assertEquals(cal.getTime(), parser.parse("0001/01/01"));
445 cal.set(10,0,1);
446 assertEquals(cal.getTime(), parser.parse("0010/01/01"));
447 cal.set(100,0,1);
448 assertEquals(cal.getTime(), parser.parse("0100/01/01"));
449 cal.set(999,0,1);
450 assertEquals(cal.getTime(), parser.parse("0999/01/01"));
451 }
452
453 /**
454 * @throws ParseException
455 */
456 @Test
457 public void testMilleniumBug() throws ParseException {
458 final DateParser parser = getInstance(DMY_DOT);
459 final Calendar cal = Calendar.getInstance();
460 cal.clear();
461
462 cal.set(1000,0,1);
463 assertEquals(cal.getTime(), parser.parse("01.01.1000"));
464 }
465
466 @Test
467 public void testLang303() throws ParseException {
468 DateParser parser = getInstance(YMD_SLASH);
469 final Calendar cal = Calendar.getInstance();
470 cal.set(2004, 11, 31);
471
472 final Date date = parser.parse("2004/11/31");
473
474 parser = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) parser));
475 assertEquals(date, parser.parse("2004/11/31"));
476 }
477
478 @Test
479 public void testLang538() throws ParseException {
480 final DateParser parser = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", GMT);
481
482 final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8"));
483 cal.clear();
484 cal.set(2009, 9, 16, 8, 42, 16);
485
486 assertEquals(cal.getTime(), parser.parse("2009-10-16T16:42:16.000Z"));
487 }
488
489 @Test
490 public void testEquals() {
491 final DateParser parser1= getInstance(YMD_SLASH);
492 final DateParser parser2= getInstance(YMD_SLASH);
493
494 assertEquals(parser1, parser2);
495 assertEquals(parser1.hashCode(), parser2.hashCode());
496
497 assertFalse(parser1.equals(new Object()));
498 }
499
500 @Test
501 public void testToStringContainsName() {
502 final DateParser parser= getInstance(YMD_SLASH);
503 assertTrue(parser.toString().startsWith("FastDate"));
504 }
505
506 @Test
507 public void testPatternMatches() {
508 final DateParser parser= getInstance(yMdHmsSZ);
509 assertEquals(yMdHmsSZ, parser.getPattern());
510 }
511
512 @Test
513 public void testLocaleMatches() {
514 final DateParser parser= getInstance(yMdHmsSZ, SWEDEN);
515 assertEquals(SWEDEN, parser.getLocale());
516 }
517
518 @Test
519 public void testTimeZoneMatches() {
520 final DateParser parser= getInstance(yMdHmsSZ, REYKJAVIK);
521 assertEquals(REYKJAVIK, parser.getTimeZone());
522 }
523 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import static org.junit.Assert.assertNotNull;
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertTrue;
22
23 import java.io.Serializable;
24 import java.text.SimpleDateFormat;
25 import java.util.Calendar;
26 import java.util.Date;
27 import java.util.GregorianCalendar;
28 import java.util.Locale;
29 import java.util.TimeZone;
30
31 import org.apache.commons.lang3.SerializationUtils;
32 import org.junit.Test;
33
34 /**
35 * Unit tests {@link org.apache.commons.lang3.time.FastDatePrinter}.
36 *
37 * @version $Id: FastDatePrinterTest.java 1552661 2013-12-20 13:36:30Z britter $
38 * @since 3.0
39 */
40 public class FastDatePrinterTest {
41
42 private static final String YYYY_MM_DD = "yyyy/MM/dd";
43 private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
44 private static final Locale SWEDEN = new Locale("sv", "SE");
45
46 DatePrinter getInstance(final String format) {
47 return getInstance(format, TimeZone.getDefault(), Locale.getDefault());
48 }
49
50 private DatePrinter getDateInstance(final int dateStyle, final Locale locale) {
51 return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault());
52 }
53
54 private DatePrinter getInstance(final String format, final Locale locale) {
55 return getInstance(format, TimeZone.getDefault(), locale);
56 }
57
58 private DatePrinter getInstance(final String format, final TimeZone timeZone) {
59 return getInstance(format, timeZone, Locale.getDefault());
60 }
61
62 /**
63 * Override this method in derived tests to change the construction of instances
64 * @param format
65 * @param timeZone
66 * @param locale
67 * @return
68 */
69 protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale) {
70 return new FastDatePrinter(format, timeZone, locale);
71 }
72
73 @Test
74 public void testFormat() {
75 final Locale realDefaultLocale = Locale.getDefault();
76 final TimeZone realDefaultZone = TimeZone.getDefault();
77 try {
78 Locale.setDefault(Locale.US);
79 TimeZone.setDefault(NEW_YORK);
80
81 final GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20);
82 final GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00);
83 final Date date1 = cal1.getTime();
84 final Date date2 = cal2.getTime();
85 final long millis1 = date1.getTime();
86 final long millis2 = date2.getTime();
87
88 DatePrinter fdf = getInstance("yyyy-MM-dd'T'HH:mm:ss");
89 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
90 assertEquals(sdf.format(date1), fdf.format(date1));
91 assertEquals("2003-01-10T15:33:20", fdf.format(date1));
92 assertEquals("2003-01-10T15:33:20", fdf.format(cal1));
93 assertEquals("2003-01-10T15:33:20", fdf.format(millis1));
94 assertEquals("2003-07-10T09:00:00", fdf.format(date2));
95 assertEquals("2003-07-10T09:00:00", fdf.format(cal2));
96 assertEquals("2003-07-10T09:00:00", fdf.format(millis2));
97
98 fdf = getInstance("Z");
99 assertEquals("-0500", fdf.format(date1));
100 assertEquals("-0500", fdf.format(cal1));
101 assertEquals("-0500", fdf.format(millis1));
102
103 assertEquals("-0400", fdf.format(date2));
104 assertEquals("-0400", fdf.format(cal2));
105 assertEquals("-0400", fdf.format(millis2));
106
107 fdf = getInstance("ZZ");
108 assertEquals("-05:00", fdf.format(date1));
109 assertEquals("-05:00", fdf.format(cal1));
110 assertEquals("-05:00", fdf.format(millis1));
111
112 assertEquals("-04:00", fdf.format(date2));
113 assertEquals("-04:00", fdf.format(cal2));
114 assertEquals("-04:00", fdf.format(millis2));
115
116 final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" +
117 " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z";
118 fdf = getInstance(pattern);
119 sdf = new SimpleDateFormat(pattern);
120 // SDF bug fix starting with Java 7
121 assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1));
122 assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2));
123 } finally {
124 Locale.setDefault(realDefaultLocale);
125 TimeZone.setDefault(realDefaultZone);
126 }
127 }
128
129 /**
130 * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
131 */
132 @Test
133 public void testShortDateStyleWithLocales() {
134 final Locale usLocale = Locale.US;
135 final Locale swedishLocale = new Locale("sv", "SE");
136 final Calendar cal = Calendar.getInstance();
137 cal.set(2004, 1, 3);
138 DatePrinter fdf = getDateInstance(FastDateFormat.SHORT, usLocale);
139 assertEquals("2/3/04", fdf.format(cal));
140
141 fdf = getDateInstance(FastDateFormat.SHORT, swedishLocale);
142 assertEquals("2004-02-03", fdf.format(cal));
143
144 }
145
146 /**
147 * Tests that pre-1000AD years get padded with yyyy
148 */
149 @Test
150 public void testLowYearPadding() {
151 final Calendar cal = Calendar.getInstance();
152 final DatePrinter format = getInstance(YYYY_MM_DD);
153
154 cal.set(1,0,1);
155 assertEquals("0001/01/01", format.format(cal));
156 cal.set(10,0,1);
157 assertEquals("0010/01/01", format.format(cal));
158 cal.set(100,0,1);
159 assertEquals("0100/01/01", format.format(cal));
160 cal.set(999,0,1);
161 assertEquals("0999/01/01", format.format(cal));
162 }
163 /**
164 * Show Bug #39410 is solved
165 */
166 @Test
167 public void testMilleniumBug() {
168 final Calendar cal = Calendar.getInstance();
169 final DatePrinter format = getInstance("dd.MM.yyyy");
170
171 cal.set(1000,0,1);
172 assertEquals("01.01.1000", format.format(cal));
173 }
174
175 /**
176 * testLowYearPadding showed that the date was buggy
177 * This test confirms it, getting 366 back as a date
178 */
179 @Test
180 public void testSimpleDate() {
181 final Calendar cal = Calendar.getInstance();
182 final DatePrinter format = getInstance(YYYY_MM_DD);
183
184 cal.set(2004,11,31);
185 assertEquals("2004/12/31", format.format(cal));
186 cal.set(999,11,31);
187 assertEquals("0999/12/31", format.format(cal));
188 cal.set(1,2,2);
189 assertEquals("0001/03/02", format.format(cal));
190 }
191
192 @Test
193 public void testLang303() {
194 final Calendar cal = Calendar.getInstance();
195 cal.set(2004, 11, 31);
196
197 DatePrinter format = getInstance(YYYY_MM_DD);
198 final String output = format.format(cal);
199
200 format = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) format));
201 assertEquals(output, format.format(cal));
202 }
203
204 @Test
205 public void testLang538() {
206 // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16)
207 // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone
208 final GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
209 cal.clear();
210 cal.set(2009, 9, 16, 8, 42, 16);
211
212 final DatePrinter format = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
213 assertEquals("dateTime", "2009-10-16T16:42:16.000Z", format.format(cal.getTime()));
214 assertEquals("dateTime", "2009-10-16T08:42:16.000Z", format.format(cal));
215 }
216
217 @Test
218 public void testLang645() {
219 final Locale locale = new Locale("sv", "SE");
220
221 final Calendar cal = Calendar.getInstance();
222 cal.set(2010, 0, 1, 12, 0, 0);
223 final Date d = cal.getTime();
224
225 final DatePrinter fdf = getInstance("EEEE', week 'ww", locale);
226
227 assertEquals("fredag, week 53", fdf.format(d));
228 }
229
230 @Test
231 public void testEquals() {
232 final DatePrinter printer1= getInstance(YYYY_MM_DD);
233 final DatePrinter printer2= getInstance(YYYY_MM_DD);
234
235 assertEquals(printer1, printer2);
236 assertEquals(printer1.hashCode(), printer2.hashCode());
237
238 assertFalse(printer1.equals(new Object()));
239 }
240
241 @Test
242 public void testToStringContainsName() {
243 final DatePrinter printer= getInstance(YYYY_MM_DD);
244 assertTrue(printer.toString().startsWith("FastDate"));
245 }
246
247 @Test
248 public void testPatternMatches() {
249 final DatePrinter printer= getInstance(YYYY_MM_DD);
250 assertEquals(YYYY_MM_DD, printer.getPattern());
251 }
252
253 @Test
254 public void testLocaleMatches() {
255 final DatePrinter printer= getInstance(YYYY_MM_DD, SWEDEN);
256 assertEquals(SWEDEN, printer.getLocale());
257 }
258
259 @Test
260 public void testTimeZoneMatches() {
261 final DatePrinter printer= getInstance(YYYY_MM_DD, NEW_YORK);
262 assertEquals(NEW_YORK, printer.getTimeZone());
263 }
264
265 @Test
266 public void testCalendarTimezoneRespected() {
267 final String[] availableZones = TimeZone.getAvailableIDs();
268 final TimeZone currentZone = TimeZone.getDefault();
269
270 TimeZone anotherZone = null;
271 for (final String zone : availableZones) {
272 if (!zone.equals(currentZone.getID())) {
273 anotherZone = TimeZone.getTimeZone(zone);
274 }
275 }
276
277 assertNotNull("Cannot find another timezone", anotherZone);
278
279 final String pattern = "h:mma z";
280 final Calendar cal = Calendar.getInstance(anotherZone);
281
282 final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
283 sdf.setTimeZone(anotherZone);
284 final String expectedValue = sdf.format(cal.getTime());
285 final String actualValue = FastDateFormat.getInstance(pattern).format(cal);
286 assertEquals(expectedValue, actualValue);
287 }
288 }
1515 */
1616 package org.apache.commons.lang3.time;
1717
18 import junit.framework.Assert;
19 import junit.framework.TestCase;
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertTrue;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.fail;
22 import org.junit.Assert;
23
24 import org.junit.Test;
2025
2126 /**
2227 * TestCase for StopWatch.
2328 *
24 * @version $Id: StopWatchTest.java 1088899 2011-04-05 05:31:27Z bayard $
29 * @version $Id: StopWatchTest.java 1535555 2013-10-24 21:23:40Z bayard $
2530 */
26 public class StopWatchTest extends TestCase {
27
28 public StopWatchTest(String s) {
29 super(s);
30 }
31 public class StopWatchTest {
3132
3233 //-----------------------------------------------------------------------
34 @Test
3335 public void testStopWatchSimple(){
34 StopWatch watch = new StopWatch();
35 watch.start();
36 try {Thread.sleep(550);} catch (InterruptedException ex) {}
37 watch.stop();
38 long time = watch.getTime();
36 final StopWatch watch = new StopWatch();
37 watch.start();
38 try {Thread.sleep(550);} catch (final InterruptedException ex) {}
39 watch.stop();
40 final long time = watch.getTime();
3941 assertEquals(time, watch.getTime());
4042
4143 assertTrue(time >= 500);
4547 assertEquals(0, watch.getTime());
4648 }
4749
50 @Test
4851 public void testStopWatchSimpleGet(){
49 StopWatch watch = new StopWatch();
52 final StopWatch watch = new StopWatch();
5053 assertEquals(0, watch.getTime());
5154 assertEquals("0:00:00.000", watch.toString());
5255
5356 watch.start();
54 try {Thread.sleep(500);} catch (InterruptedException ex) {}
57 try {Thread.sleep(500);} catch (final InterruptedException ex) {}
5558 assertTrue(watch.getTime() < 2000);
5659 }
5760
61 @Test
5862 public void testStopWatchSplit(){
59 StopWatch watch = new StopWatch();
60 watch.start();
61 try {Thread.sleep(550);} catch (InterruptedException ex) {}
63 final StopWatch watch = new StopWatch();
64 watch.start();
65 try {Thread.sleep(550);} catch (final InterruptedException ex) {}
6266 watch.split();
63 long splitTime = watch.getSplitTime();
64 String splitStr = watch.toSplitString();
65 try {Thread.sleep(550);} catch (InterruptedException ex) {}
67 final long splitTime = watch.getSplitTime();
68 final String splitStr = watch.toSplitString();
69 try {Thread.sleep(550);} catch (final InterruptedException ex) {}
6670 watch.unsplit();
67 try {Thread.sleep(550);} catch (InterruptedException ex) {}
68 watch.stop();
69 long totalTime = watch.getTime();
71 try {Thread.sleep(550);} catch (final InterruptedException ex) {}
72 watch.stop();
73 final long totalTime = watch.getTime();
7074
7175 assertEquals("Formatted split string not the correct length",
7276 splitStr.length(), 11);
7680 assertTrue(totalTime < 1900);
7781 }
7882
83 @Test
7984 public void testStopWatchSuspend(){
80 StopWatch watch = new StopWatch();
81 watch.start();
82 try {Thread.sleep(550);} catch (InterruptedException ex) {}
85 final StopWatch watch = new StopWatch();
86 watch.start();
87 try {Thread.sleep(550);} catch (final InterruptedException ex) {}
8388 watch.suspend();
84 long suspendTime = watch.getTime();
85 try {Thread.sleep(550);} catch (InterruptedException ex) {}
89 final long suspendTime = watch.getTime();
90 try {Thread.sleep(550);} catch (final InterruptedException ex) {}
8691 watch.resume();
87 try {Thread.sleep(550);} catch (InterruptedException ex) {}
88 watch.stop();
89 long totalTime = watch.getTime();
92 try {Thread.sleep(550);} catch (final InterruptedException ex) {}
93 watch.stop();
94 final long totalTime = watch.getTime();
9095
9196 assertTrue(suspendTime >= 500);
9297 assertTrue(suspendTime < 700);
9499 assertTrue(totalTime < 1300);
95100 }
96101
102 @Test
97103 public void testLang315() {
98 StopWatch watch = new StopWatch();
99 watch.start();
100 try {Thread.sleep(200);} catch (InterruptedException ex) {}
104 final StopWatch watch = new StopWatch();
105 watch.start();
106 try {Thread.sleep(200);} catch (final InterruptedException ex) {}
101107 watch.suspend();
102 long suspendTime = watch.getTime();
103 try {Thread.sleep(200);} catch (InterruptedException ex) {}
104 watch.stop();
105 long totalTime = watch.getTime();
108 final long suspendTime = watch.getTime();
109 try {Thread.sleep(200);} catch (final InterruptedException ex) {}
110 watch.stop();
111 final long totalTime = watch.getTime();
106112 assertTrue( suspendTime == totalTime );
107113 }
108114
109115 // test bad states
116 @Test
110117 public void testBadStates() {
111 StopWatch watch = new StopWatch();
118 final StopWatch watch = new StopWatch();
112119 try {
113120 watch.stop();
114121 fail("Calling stop on an unstarted StopWatch should throw an exception. ");
115 } catch(IllegalStateException ise) {
122 } catch(final IllegalStateException ise) {
116123 // expected
117124 }
118125
119126 try {
120127 watch.stop();
121128 fail("Calling stop on an unstarted StopWatch should throw an exception. ");
122 } catch(IllegalStateException ise) {
129 } catch(final IllegalStateException ise) {
123130 // expected
124131 }
125132
126133 try {
127134 watch.suspend();
128135 fail("Calling suspend on an unstarted StopWatch should throw an exception. ");
129 } catch(IllegalStateException ise) {
136 } catch(final IllegalStateException ise) {
130137 // expected
131138 }
132139
133140 try {
134141 watch.split();
135142 fail("Calling split on a non-running StopWatch should throw an exception. ");
136 } catch(IllegalStateException ise) {
143 } catch(final IllegalStateException ise) {
137144 // expected
138145 }
139146
140147 try {
141148 watch.unsplit();
142149 fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
143 } catch(IllegalStateException ise) {
150 } catch(final IllegalStateException ise) {
144151 // expected
145152 }
146153
147154 try {
148155 watch.resume();
149156 fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
150 } catch(IllegalStateException ise) {
157 } catch(final IllegalStateException ise) {
151158 // expected
152159 }
153160
156163 try {
157164 watch.start();
158165 fail("Calling start on a started StopWatch should throw an exception. ");
159 } catch(IllegalStateException ise) {
166 } catch(final IllegalStateException ise) {
160167 // expected
161168 }
162169
163170 try {
164171 watch.unsplit();
165172 fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
166 } catch(IllegalStateException ise) {
173 } catch(final IllegalStateException ise) {
167174 // expected
168175 }
169176
170177 try {
171178 watch.getSplitTime();
172179 fail("Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
173 } catch(IllegalStateException ise) {
180 } catch(final IllegalStateException ise) {
174181 // expected
175182 }
176183
177184 try {
178185 watch.resume();
179186 fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
180 } catch(IllegalStateException ise) {
187 } catch(final IllegalStateException ise) {
181188 // expected
182189 }
183190
186193 try {
187194 watch.start();
188195 fail("Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
189 } catch(IllegalStateException ise) {
190 // expected
191 }
192 }
193
196 } catch(final IllegalStateException ise) {
197 // expected
198 }
199 }
200
201 @Test
194202 public void testGetStartTime() {
195 long beforeStopWatch = System.currentTimeMillis();
196 StopWatch watch = new StopWatch();
203 final long beforeStopWatch = System.currentTimeMillis();
204 final StopWatch watch = new StopWatch();
197205 try {
198206 watch.getStartTime();
199207 fail("Calling getStartTime on an unstarted StopWatch should throw an exception");
200 } catch (IllegalStateException expected) {
208 } catch (final IllegalStateException expected) {
201209 // expected
202210 }
203211 watch.start();
204212 try {
205213 watch.getStartTime();
206214 Assert.assertTrue(watch.getStartTime() >= beforeStopWatch);
207 } catch (IllegalStateException ex) {
215 } catch (final IllegalStateException ex) {
208216 fail("Start time should be available: " + ex.getMessage());
209217 }
210218 watch.reset();
211219 try {
212220 watch.getStartTime();
213221 fail("Calling getStartTime on a reset, but unstarted StopWatch should throw an exception");
214 } catch (IllegalStateException expected) {
215 // expected
216 }
222 } catch (final IllegalStateException expected) {
223 // expected
224 }
225 }
226
227 @Test
228 public void testBooleanStates() {
229 final StopWatch watch = new StopWatch();
230 assertFalse(watch.isStarted());
231 assertFalse(watch.isSuspended());
232 assertTrue(watch.isStopped());
233
234 watch.start();
235 assertTrue(watch.isStarted());
236 assertFalse(watch.isSuspended());
237 assertFalse(watch.isStopped());
238
239 watch.suspend();
240 assertTrue(watch.isStarted());
241 assertTrue(watch.isSuspended());
242 assertFalse(watch.isStopped());
243
244 watch.stop();
245 assertFalse(watch.isStarted());
246 assertFalse(watch.isSuspended());
247 assertTrue(watch.isStopped());
217248 }
218249
219250 }
2929
3030 /**
3131 * Test the Pair class.
32 * @version $Id: ImmutablePairTest.java 1091531 2011-04-12 18:29:49Z ggregory $
32 * @version $Id: ImmutablePairTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3333 */
3434 public class ImmutablePairTest {
3535
3636 @Test
3737 public void testBasic() throws Exception {
38 ImmutablePair<Integer, String> pair = new ImmutablePair<Integer, String>(0, "foo");
38 final ImmutablePair<Integer, String> pair = new ImmutablePair<Integer, String>(0, "foo");
3939 assertEquals(0, pair.left.intValue());
4040 assertEquals(0, pair.getLeft().intValue());
4141 assertEquals("foo", pair.right);
4242 assertEquals("foo", pair.getRight());
43 ImmutablePair<Object, String> pair2 = new ImmutablePair<Object, String>(null, "bar");
43 final ImmutablePair<Object, String> pair2 = new ImmutablePair<Object, String>(null, "bar");
4444 assertNull(pair2.left);
4545 assertNull(pair2.getLeft());
4646 assertEquals("bar", pair2.right);
4949
5050 @Test
5151 public void testPairOf() throws Exception {
52 ImmutablePair<Integer, String> pair = ImmutablePair.of(0, "foo");
52 final ImmutablePair<Integer, String> pair = ImmutablePair.of(0, "foo");
5353 assertEquals(0, pair.left.intValue());
5454 assertEquals(0, pair.getLeft().intValue());
5555 assertEquals("foo", pair.right);
5656 assertEquals("foo", pair.getRight());
57 ImmutablePair<Object, String> pair2 = ImmutablePair.of(null, "bar");
57 final ImmutablePair<Object, String> pair2 = ImmutablePair.of(null, "bar");
5858 assertNull(pair2.left);
5959 assertNull(pair2.getLeft());
6060 assertEquals("bar", pair2.right);
6767 assertFalse(ImmutablePair.of("foo", 0).equals(ImmutablePair.of("foo", null)));
6868 assertFalse(ImmutablePair.of("foo", "bar").equals(ImmutablePair.of("xyz", "bar")));
6969
70 ImmutablePair<String, String> p = ImmutablePair.of("foo", "bar");
70 final ImmutablePair<String, String> p = ImmutablePair.of("foo", "bar");
7171 assertTrue(p.equals(p));
7272 assertFalse(p.equals(new Object()));
7373 }
8888 @Test
8989 @SuppressWarnings("unchecked")
9090 public void testSerialization() throws Exception {
91 ImmutablePair<Integer, String> origPair = ImmutablePair.of(0, "foo");
92 ByteArrayOutputStream baos = new ByteArrayOutputStream();
93 ObjectOutputStream out = new ObjectOutputStream(baos);
91 final ImmutablePair<Integer, String> origPair = ImmutablePair.of(0, "foo");
92 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
93 final ObjectOutputStream out = new ObjectOutputStream(baos);
9494 out.writeObject(origPair);
95 ImmutablePair<Integer, String> deserializedPair = (ImmutablePair<Integer, String>) new ObjectInputStream(
95 final ImmutablePair<Integer, String> deserializedPair = (ImmutablePair<Integer, String>) new ObjectInputStream(
9696 new ByteArrayInputStream(baos.toByteArray())).readObject();
9797 assertEquals(origPair, deserializedPair);
9898 assertEquals(origPair.hashCode(), deserializedPair.hashCode());
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.tuple;
17
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNull;
21 import static org.junit.Assert.assertTrue;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27
28 import org.junit.Test;
29
30 /**
31 * Test the Triple class.
32 * @version $Id: ImmutableTripleTest.java 1552635 2013-12-20 13:02:03Z britter $
33 */
34 public class ImmutableTripleTest {
35
36 @Test
37 public void testBasic() throws Exception {
38 final ImmutableTriple<Integer, String, Boolean> triple = new ImmutableTriple<Integer, String, Boolean>(0, "foo", Boolean.TRUE);
39 assertEquals(0, triple.left.intValue());
40 assertEquals(0, triple.getLeft().intValue());
41 assertEquals("foo", triple.middle);
42 assertEquals("foo", triple.getMiddle());
43 assertEquals(Boolean.TRUE, triple.right);
44 assertEquals(Boolean.TRUE, triple.getRight());
45 final ImmutableTriple<Object, String, Integer> triple2 = new ImmutableTriple<Object, String, Integer>(null, "bar", 42);
46 assertNull(triple2.left);
47 assertNull(triple2.getLeft());
48 assertEquals("bar", triple2.middle);
49 assertEquals("bar", triple2.getMiddle());
50 assertEquals(new Integer(42), triple2.right);
51 assertEquals(new Integer(42), triple2.getRight());
52 }
53
54 @Test
55 public void testTripleOf() throws Exception {
56 final ImmutableTriple<Integer, String, Boolean> triple = ImmutableTriple.of(0, "foo", Boolean.FALSE);
57 assertEquals(0, triple.left.intValue());
58 assertEquals(0, triple.getLeft().intValue());
59 assertEquals("foo", triple.middle);
60 assertEquals("foo", triple.getMiddle());
61 assertEquals(Boolean.FALSE, triple.right);
62 assertEquals(Boolean.FALSE, triple.getRight());
63 final ImmutableTriple<Object, String, Boolean> triple2 = ImmutableTriple.of(null, "bar", Boolean.TRUE);
64 assertNull(triple2.left);
65 assertNull(triple2.getLeft());
66 assertEquals("bar", triple2.middle);
67 assertEquals("bar", triple2.getMiddle());
68 assertEquals(Boolean.TRUE, triple2.right);
69 assertEquals(Boolean.TRUE, triple2.getRight());
70 }
71
72 @Test
73 public void testEquals() throws Exception {
74 assertEquals(ImmutableTriple.of(null, "foo", 42), ImmutableTriple.of(null, "foo", 42));
75 assertFalse(ImmutableTriple.of("foo", 0, Boolean.TRUE).equals(ImmutableTriple.of("foo", null, null)));
76 assertFalse(ImmutableTriple.of("foo", "bar", "baz").equals(ImmutableTriple.of("xyz", "bar", "blo")));
77
78 final ImmutableTriple<String, String, String> p = ImmutableTriple.of("foo", "bar", "baz");
79 assertTrue(p.equals(p));
80 assertFalse(p.equals(new Object()));
81 }
82
83 @Test
84 public void testHashCode() throws Exception {
85 assertEquals(ImmutableTriple.of(null, "foo", Boolean.TRUE).hashCode(), ImmutableTriple.of(null, "foo", Boolean.TRUE).hashCode());
86 }
87
88 @Test
89 public void testToString() throws Exception {
90 assertEquals("(null,null,null)", ImmutableTriple.of(null, null, null).toString());
91 assertEquals("(null,two,null)", ImmutableTriple.of(null, "two", null).toString());
92 assertEquals("(one,null,null)", ImmutableTriple.of("one", null, null).toString());
93 assertEquals("(one,two,null)", ImmutableTriple.of("one", "two", null).toString());
94 assertEquals("(null,two,three)", ImmutableTriple.of(null, "two", "three").toString());
95 assertEquals("(one,null,three)", ImmutableTriple.of("one", null, "three").toString());
96 assertEquals("(one,two,three)", MutableTriple.of("one", "two", "three").toString());
97 }
98
99 @Test
100 @SuppressWarnings("unchecked")
101 public void testSerialization() throws Exception {
102 final ImmutableTriple<Integer, String, Boolean> origTriple = ImmutableTriple.of(0, "foo", Boolean.TRUE);
103 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
104 final ObjectOutputStream out = new ObjectOutputStream(baos);
105 out.writeObject(origTriple);
106 final ImmutableTriple<Integer, String, Boolean> deserializedTriple = (ImmutableTriple<Integer, String, Boolean>) new ObjectInputStream(
107 new ByteArrayInputStream(baos.toByteArray())).readObject();
108 assertEquals(origTriple, deserializedTriple);
109 assertEquals(origTriple.hashCode(), deserializedTriple.hashCode());
110 }
111 }
112
2929
3030 /**
3131 * Test the MutablePair class.
32 * @version $Id: MutablePairTest.java 1124337 2011-05-18 17:01:47Z mbenson $
32 * @version $Id: MutablePairTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3333 */
3434 public class MutablePairTest {
3535
3636 @Test
3737 public void testBasic() throws Exception {
38 MutablePair<Integer, String> pair = new MutablePair<Integer, String>(0, "foo");
38 final MutablePair<Integer, String> pair = new MutablePair<Integer, String>(0, "foo");
3939 assertEquals(0, pair.getLeft().intValue());
4040 assertEquals("foo", pair.getRight());
41 MutablePair<Object, String> pair2 = new MutablePair<Object, String>(null, "bar");
41 final MutablePair<Object, String> pair2 = new MutablePair<Object, String>(null, "bar");
4242 assertNull(pair2.getLeft());
4343 assertEquals("bar", pair2.getRight());
4444 }
4545
4646 @Test
4747 public void testDefault() throws Exception {
48 MutablePair<Integer, String> pair = new MutablePair<Integer, String>();
48 final MutablePair<Integer, String> pair = new MutablePair<Integer, String>();
4949 assertNull(pair.getLeft());
5050 assertNull(pair.getRight());
5151 }
5252
5353 @Test
5454 public void testMutate() throws Exception {
55 MutablePair<Integer, String> pair = new MutablePair<Integer, String>(0, "foo");
55 final MutablePair<Integer, String> pair = new MutablePair<Integer, String>(0, "foo");
5656 pair.setLeft(42);
5757 pair.setRight("bar");
5858 assertEquals(42, pair.getLeft().intValue());
6161
6262 @Test
6363 public void testPairOf() throws Exception {
64 MutablePair<Integer, String> pair = MutablePair.of(0, "foo");
64 final MutablePair<Integer, String> pair = MutablePair.of(0, "foo");
6565 assertEquals(0, pair.getLeft().intValue());
6666 assertEquals("foo", pair.getRight());
67 MutablePair<Object, String> pair2 = MutablePair.of(null, "bar");
67 final MutablePair<Object, String> pair2 = MutablePair.of(null, "bar");
6868 assertNull(pair2.getLeft());
6969 assertEquals("bar", pair2.getRight());
7070 }
7575 assertFalse(MutablePair.of("foo", 0).equals(MutablePair.of("foo", null)));
7676 assertFalse(MutablePair.of("foo", "bar").equals(MutablePair.of("xyz", "bar")));
7777
78 MutablePair<String, String> p = MutablePair.of("foo", "bar");
78 final MutablePair<String, String> p = MutablePair.of("foo", "bar");
7979 assertTrue(p.equals(p));
8080 assertFalse(p.equals(new Object()));
8181 }
9696 @Test
9797 @SuppressWarnings("unchecked")
9898 public void testSerialization() throws Exception {
99 MutablePair<Integer, String> origPair = MutablePair.of(0, "foo");
100 ByteArrayOutputStream baos = new ByteArrayOutputStream();
101 ObjectOutputStream out = new ObjectOutputStream(baos);
99 final MutablePair<Integer, String> origPair = MutablePair.of(0, "foo");
100 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
101 final ObjectOutputStream out = new ObjectOutputStream(baos);
102102 out.writeObject(origPair);
103 MutablePair<Integer, String> deserializedPair = (MutablePair<Integer, String>) new ObjectInputStream(
103 final MutablePair<Integer, String> deserializedPair = (MutablePair<Integer, String>) new ObjectInputStream(
104104 new ByteArrayInputStream(baos.toByteArray())).readObject();
105105 assertEquals(origPair, deserializedPair);
106106 assertEquals(origPair.hashCode(), deserializedPair.hashCode());
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.tuple;
17
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertNull;
21 import static org.junit.Assert.assertTrue;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27
28 import org.junit.Test;
29
30 /**
31 * Test the MutableTriple class.
32 * @version $Id: MutableTripleTest.java 1552635 2013-12-20 13:02:03Z britter $
33 */
34 public class MutableTripleTest {
35
36 @Test
37 public void testBasic() throws Exception {
38 final MutableTriple<Integer, String, Boolean> triple = new MutableTriple<Integer, String, Boolean>(0, "foo", Boolean.FALSE);
39 assertEquals(0, triple.getLeft().intValue());
40 assertEquals("foo", triple.getMiddle());
41 assertEquals(Boolean.FALSE, triple.getRight());
42 final MutableTriple<Object, String, String> triple2 = new MutableTriple<Object, String, String>(null, "bar", "hello");
43 assertNull(triple2.getLeft());
44 assertEquals("bar", triple2.getMiddle());
45 assertEquals("hello", triple2.getRight());
46 }
47
48 @Test
49 public void testDefault() throws Exception {
50 final MutableTriple<Integer, String, Boolean> triple = new MutableTriple<Integer, String, Boolean>();
51 assertNull(triple.getLeft());
52 assertNull(triple.getMiddle());
53 assertNull(triple.getRight());
54 }
55
56 @Test
57 public void testMutate() throws Exception {
58 final MutableTriple<Integer, String, Boolean> triple = new MutableTriple<Integer, String, Boolean>(0, "foo", Boolean.TRUE);
59 triple.setLeft(42);
60 triple.setMiddle("bar");
61 triple.setRight(Boolean.FALSE);
62 assertEquals(42, triple.getLeft().intValue());
63 assertEquals("bar", triple.getMiddle());
64 assertEquals(Boolean.FALSE, triple.getRight());
65 }
66
67 @Test
68 public void testTripleOf() throws Exception {
69 final MutableTriple<Integer, String, Boolean> triple = MutableTriple.of(0, "foo", Boolean.TRUE);
70 assertEquals(0, triple.getLeft().intValue());
71 assertEquals("foo", triple.getMiddle());
72 assertEquals(Boolean.TRUE, triple.getRight());
73 final MutableTriple<Object, String, String> triple2 = MutableTriple.of(null, "bar", "hello");
74 assertNull(triple2.getLeft());
75 assertEquals("bar", triple2.getMiddle());
76 assertEquals("hello", triple2.getRight());
77 }
78
79 @Test
80 public void testEquals() throws Exception {
81 assertEquals(MutableTriple.of(null, "foo", "baz"), MutableTriple.of(null, "foo", "baz"));
82 assertFalse(MutableTriple.of("foo", 0, Boolean.TRUE).equals(MutableTriple.of("foo", null, Boolean.TRUE)));
83 assertFalse(MutableTriple.of("foo", "bar", "baz").equals(MutableTriple.of("xyz", "bar", "baz")));
84 assertFalse(MutableTriple.of("foo", "bar", "baz").equals(MutableTriple.of("foo", "bar", "blo")));
85
86 final MutableTriple<String, String, String> p = MutableTriple.of("foo", "bar", "baz");
87 assertTrue(p.equals(p));
88 assertFalse(p.equals(new Object()));
89 }
90
91 @Test
92 public void testHashCode() throws Exception {
93 assertEquals(MutableTriple.of(null, "foo", "baz").hashCode(), MutableTriple.of(null, "foo", "baz").hashCode());
94 }
95
96 @Test
97 public void testToString() throws Exception {
98 assertEquals("(null,null,null)", MutableTriple.of(null, null, null).toString());
99 assertEquals("(null,two,null)", MutableTriple.of(null, "two", null).toString());
100 assertEquals("(one,null,null)", MutableTriple.of("one", null, null).toString());
101 assertEquals("(one,two,null)", MutableTriple.of("one", "two", null).toString());
102 assertEquals("(null,two,three)", MutableTriple.of(null, "two", "three").toString());
103 assertEquals("(one,null,three)", MutableTriple.of("one", null, "three").toString());
104 assertEquals("(one,two,three)", MutableTriple.of("one", "two", "three").toString());
105 }
106
107 @Test
108 @SuppressWarnings("unchecked")
109 public void testSerialization() throws Exception {
110 final MutableTriple<Integer, String, Boolean> origTriple = MutableTriple.of(0, "foo", Boolean.TRUE);
111 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
112 final ObjectOutputStream out = new ObjectOutputStream(baos);
113 out.writeObject(origTriple);
114 final MutableTriple<Integer, String, Boolean> deserializedTriple = (MutableTriple<Integer, String, Boolean>) new ObjectInputStream(
115 new ByteArrayInputStream(baos.toByteArray())).readObject();
116 assertEquals(origTriple, deserializedTriple);
117 assertEquals(origTriple.hashCode(), deserializedTriple.hashCode());
118 }
119 }
120
3030 /**
3131 * Test the Pair class.
3232 *
33 * @version $Id: PairTest.java 1199724 2011-11-09 12:51:52Z sebb $
33 * @version $Id: PairTest.java 1436770 2013-01-22 07:09:45Z ggregory $
3434 */
3535 public class PairTest {
3636
3737 @Test
3838 public void testPairOf() throws Exception {
39 Pair<Integer, String> pair = Pair.of(0, "foo");
39 final Pair<Integer, String> pair = Pair.of(0, "foo");
4040 assertTrue(pair instanceof ImmutablePair<?, ?>);
4141 assertEquals(0, ((ImmutablePair<Integer, String>) pair).left.intValue());
4242 assertEquals("foo", ((ImmutablePair<Integer, String>) pair).right);
43 Pair<Object, String> pair2 = Pair.of(null, "bar");
43 final Pair<Object, String> pair2 = Pair.of(null, "bar");
4444 assertTrue(pair2 instanceof ImmutablePair<?, ?>);
4545 assertNull(((ImmutablePair<Object, String>) pair2).left);
4646 assertEquals("bar", ((ImmutablePair<Object, String>) pair2).right);
4848
4949 @Test
5050 public void testCompatibilityBetweenPairs() throws Exception {
51 Pair<Integer, String> pair = ImmutablePair.of(0, "foo");
52 Pair<Integer, String> pair2 = MutablePair.of(0, "foo");
51 final Pair<Integer, String> pair = ImmutablePair.of(0, "foo");
52 final Pair<Integer, String> pair2 = MutablePair.of(0, "foo");
5353 assertEquals(pair, pair2);
5454 assertEquals(pair.hashCode(), pair2.hashCode());
55 HashSet<Pair<Integer, String>> set = new HashSet<Pair<Integer, String>>();
55 final HashSet<Pair<Integer, String>> set = new HashSet<Pair<Integer, String>>();
5656 set.add(pair);
5757 assertTrue(set.contains(pair2));
5858
6363
6464 @Test
6565 public void testMapEntry() throws Exception {
66 Pair<Integer, String> pair = ImmutablePair.of(0, "foo");
67 HashMap<Integer, String> map = new HashMap<Integer, String>();
66 final Pair<Integer, String> pair = ImmutablePair.of(0, "foo");
67 final HashMap<Integer, String> map = new HashMap<Integer, String>();
6868 map.put(0, "foo");
69 Entry<Integer, String> entry = map.entrySet().iterator().next();
69 final Entry<Integer, String> entry = map.entrySet().iterator().next();
7070 assertEquals(pair, entry);
7171 assertEquals(pair.hashCode(), entry.hashCode());
7272 }
7373
7474 @Test
7575 public void testComparable1() throws Exception {
76 Pair<String, String> pair1 = Pair.of("A", "D");
77 Pair<String, String> pair2 = Pair.of("B", "C");
76 final Pair<String, String> pair1 = Pair.of("A", "D");
77 final Pair<String, String> pair2 = Pair.of("B", "C");
7878 assertTrue(pair1.compareTo(pair1) == 0);
7979 assertTrue(pair1.compareTo(pair2) < 0);
8080 assertTrue(pair2.compareTo(pair2) == 0);
8383
8484 @Test
8585 public void testComparable2() throws Exception {
86 Pair<String, String> pair1 = Pair.of("A", "C");
87 Pair<String, String> pair2 = Pair.of("A", "D");
86 final Pair<String, String> pair1 = Pair.of("A", "C");
87 final Pair<String, String> pair2 = Pair.of("A", "D");
8888 assertTrue(pair1.compareTo(pair1) == 0);
8989 assertTrue(pair1.compareTo(pair2) < 0);
9090 assertTrue(pair2.compareTo(pair2) == 0);
9393
9494 @Test
9595 public void testToString() throws Exception {
96 Pair<String, String> pair = Pair.of("Key", "Value");
96 final Pair<String, String> pair = Pair.of("Key", "Value");
9797 assertEquals("(Key,Value)", pair.toString());
9898 }
9999
100100 @Test
101101 public void testToStringCustom() throws Exception {
102 Calendar date = Calendar.getInstance();
102 final Calendar date = Calendar.getInstance();
103103 date.set(2011, Calendar.APRIL, 25);
104 Pair<String, Calendar> pair = Pair.of("DOB", date);
104 final Pair<String, Calendar> pair = Pair.of("DOB", date);
105105 assertEquals("Test created on " + "04-25-2011", pair.toString("Test created on %2$tm-%2$td-%2$tY"));
106106 }
107107
108108 @Test
109109 public void testFormattable_simple() throws Exception {
110 Pair<String, String> pair = Pair.of("Key", "Value");
110 final Pair<String, String> pair = Pair.of("Key", "Value");
111111 assertEquals("(Key,Value)", String.format("%1$s", pair));
112112 }
113113
114114 @Test
115115 public void testFormattable_padded() throws Exception {
116 Pair<String, String> pair = Pair.of("Key", "Value");
116 final Pair<String, String> pair = Pair.of("Key", "Value");
117117 assertEquals(" (Key,Value)", String.format("%1$20s", pair));
118118 }
119119
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.tuple;
17
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertNull;
20 import static org.junit.Assert.assertTrue;
21
22 import java.util.Calendar;
23 import java.util.HashSet;
24
25 import org.junit.Test;
26
27 /**
28 * Test the Triple class.
29 *
30 * @version $Id: TripleTest.java 1552635 2013-12-20 13:02:03Z britter $
31 */
32 public class TripleTest {
33
34 @Test
35 public void testTripleOf() throws Exception {
36 final Triple<Integer, String, Boolean> triple = Triple.of(0, "foo", Boolean.TRUE);
37 assertTrue(triple instanceof ImmutableTriple<?, ?, ?>);
38 assertEquals(0, ((ImmutableTriple<Integer, String, Boolean>) triple).left.intValue());
39 assertEquals("foo", ((ImmutableTriple<Integer, String, Boolean>) triple).middle);
40 assertEquals(Boolean.TRUE, ((ImmutableTriple<Integer, String, Boolean>) triple).right);
41 final Triple<Object, String, Long> triple2 = Triple.of(null, "bar", Long.valueOf(200L));
42 assertTrue(triple2 instanceof ImmutableTriple<?, ?, ?>);
43 assertNull(((ImmutableTriple<Object, String, Long>) triple2).left);
44 assertEquals("bar", ((ImmutableTriple<Object, String, Long>) triple2).middle);
45 assertEquals(new Long(200L), ((ImmutableTriple<Object, String, Long>) triple2).right);
46 }
47
48 @Test
49 public void testCompatibilityBetweenTriples() throws Exception {
50 final Triple<Integer, String, Boolean> triple = ImmutableTriple.of(0, "foo", Boolean.TRUE);
51 final Triple<Integer, String, Boolean> triple2 = MutableTriple.of(0, "foo", Boolean.TRUE);
52 assertEquals(triple, triple2);
53 assertEquals(triple.hashCode(), triple2.hashCode());
54 final HashSet<Triple<Integer, String, Boolean>> set = new HashSet<Triple<Integer, String, Boolean>>();
55 set.add(triple);
56 assertTrue(set.contains(triple2));
57 }
58
59 @Test
60 public void testComparable1() throws Exception {
61 final Triple<String, String, String> triple1 = Triple.of("A", "D", "A");
62 final Triple<String, String, String> triple2 = Triple.of("B", "C", "A");
63 assertTrue(triple1.compareTo(triple1) == 0);
64 assertTrue(triple1.compareTo(triple2) < 0);
65 assertTrue(triple2.compareTo(triple2) == 0);
66 assertTrue(triple2.compareTo(triple1) > 0);
67 }
68
69 @Test
70 public void testComparable2() throws Exception {
71 final Triple<String, String, String> triple1 = Triple.of("A", "C", "B");
72 final Triple<String, String, String> triple2 = Triple.of("A", "D", "B");
73 assertTrue(triple1.compareTo(triple1) == 0);
74 assertTrue(triple1.compareTo(triple2) < 0);
75 assertTrue(triple2.compareTo(triple2) == 0);
76 assertTrue(triple2.compareTo(triple1) > 0);
77 }
78
79 @Test
80 public void testComparable3() throws Exception {
81 final Triple<String, String, String> triple1 = Triple.of("A", "A", "D");
82 final Triple<String, String, String> triple2 = Triple.of("A", "B", "C");
83 assertTrue(triple1.compareTo(triple1) == 0);
84 assertTrue(triple1.compareTo(triple2) < 0);
85 assertTrue(triple2.compareTo(triple2) == 0);
86 assertTrue(triple2.compareTo(triple1) > 0);
87 }
88
89 @Test
90 public void testComparable4() throws Exception {
91 final Triple<String, String, String> triple1 = Triple.of("B", "A", "C");
92 final Triple<String, String, String> triple2 = Triple.of("B", "A", "D");
93 assertTrue(triple1.compareTo(triple1) == 0);
94 assertTrue(triple1.compareTo(triple2) < 0);
95 assertTrue(triple2.compareTo(triple2) == 0);
96 assertTrue(triple2.compareTo(triple1) > 0);
97 }
98
99 @Test
100 public void testToString() throws Exception {
101 final Triple<String, String, String> triple = Triple.of("Key", "Something", "Value");
102 assertEquals("(Key,Something,Value)", triple.toString());
103 }
104
105 @Test
106 public void testToStringCustom() throws Exception {
107 final Calendar date = Calendar.getInstance();
108 date.set(2011, Calendar.APRIL, 25);
109 final Triple<String, String, Calendar> triple = Triple.of("DOB", "string", date);
110 assertEquals("Test created on " + "04-25-2011", triple.toString("Test created on %3$tm-%3$td-%3$tY"));
111 }
112
113 @Test
114 public void testFormattable_simple() throws Exception {
115 final Triple<String, String, String> triple = Triple.of("Key", "Something", "Value");
116 assertEquals("(Key,Something,Value)", String.format("%1$s", triple));
117 }
118
119 @Test
120 public void testFormattable_padded() throws Exception {
121 final Triple<String, String, String> triple = Triple.of("Key", "Something", "Value");
122 assertEquals(" (Key,Something,Value)", String.format("%1$30s", triple));
123 }
124
125 }
126